2011-08-20 54 views
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; 

我想设置上面列表中返回的值的五个变量。怎么样?

回答

1

我还没有实际使用JDBCTemplate,但根据the documentationqueryForList将返回MapList 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)。

+0

two =(int)row.get(“two”)会抛出错误。由于该值是一个对象。对象到int分析无效。 – Nik

+0

@Nikunj:谢谢,你正在阅读帖子的第一个副本,在我的早晨大脑中,这是依靠自动装箱。但是自动装箱在这里不适用,所以我解决了它。 :-) –

+0

@T。 J. Crowder:谢谢..它的工作..张贴在牧场上的答案也与信贷给你:) :) – Nik