如何为变量分配列表中的值?

发布于 2024-11-30 10:32:51 字数 439 浏览 0 评论 0原文

我正在运行此代码:

int key = 25;
String query = "Select one, two, three, four, five from myTable where key=?";
List<Map<String,Object>> data = jdbcTemplate.queryForList(query, new Object[]{key});

//one is string, two is int, three is character, four is double, five is string
String one = null;
int two = 0;
char three = '\u0000';
double four = 0.0;
String five = null;

我想使用列表中返回的值设置上面的五个变量。如何?

I am running this code:

int key = 25;
String query = "Select one, two, three, four, five from myTable where key=?";
List<Map<String,Object>> data = jdbcTemplate.queryForList(query, new Object[]{key});

//one is string, two is int, three is character, four is double, five is string
String one = null;
int two = 0;
char three = '\u0000';
double four = 0.0;
String five = null;

I want to set the five variables above with the values returned in the list. How?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

摇划花蜜的午后 2024-12-07 10:32:51

我实际上并没有使用JDBCTemplate,但是根据文档, queryForList将返回一个 List地图 a>s,每个 Map 中的键是列。

因此,要从返回的第一个行中分配这些变量:

Map<String,Object> row = data.get(0);
String one  = (String)row.get("one");

//these will not work -- Integer, Double incompatible with String
/* int two     = ((Integer)row.get("two")).intValue();
double four = ((Double)row.get("four")).doubleValue(); */

//correct method
int two     = Integer.parseInt((String)row.get("two"));
double four = Double.parseDouble((String)row.get("four"));

char three  = ((Character)row.get("three")).charValue();
    String five = (String)row.get("five");

如您所见,对于对象类型,您应该能够进行强制转换。对于基元,我已转换为对象等效项,然后使用该对象等效项的方法来获取底层基元(因此对于 int,转换为 Integer 然后使用 intValue< /a>)。

I haven't actually used JDBCTemplate, but according to the documentation, queryForList will return a List of Maps, with the keys in each Map being the names of the columns.

So to assign those variables from the first returned row:

Map<String,Object> row = data.get(0);
String one  = (String)row.get("one");

//these will not work -- Integer, Double incompatible with String
/* int two     = ((Integer)row.get("two")).intValue();
double four = ((Double)row.get("four")).doubleValue(); */

//correct method
int two     = Integer.parseInt((String)row.get("two"));
double four = Double.parseDouble((String)row.get("four"));

char three  = ((Character)row.get("three")).charValue();
    String five = (String)row.get("five");

As you can see, for the object types, you should just be able to cast. For the primitives, I've cast to the object equivalent and then used that object equivalent's method for getting the underlying primitive (so for int, cast to Integer and then use intValue).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文