我正在运行此代码:
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;
我想用列表中返回的值设置上面的五个变量。怎么样?
答案 0 :(得分:1)
我实际上并未使用JDBCTemplate
,但根据the documentation,queryForList
会返回List
Map
个,其中每个都有Integer
个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
,转换为intValue
然后使用{{3}})。