在迭代Java中的结果集时,比result.getString()更好的方法 [英] Any better approach rather than result.getString() while iterating a result set in java
问题描述
我在一个表中有6列.我有一个选择查询,该查询从表中选择一些记录.遍历结果集时,im使用以下逻辑提取列中的值:
I have 6 columns in a table. I have a select query which selects some records from the table. While iterating over the result set, im using the following logic to extract the values in the columns:
Statement select = conn.createStatement();
ResultSet result = select.executeQuery
("SELECT * FROM D724933.ECOCHECKS WHERE ECO = '"+localeco+"' AND CHK_TOOL = '"+checknames[i]+"'");
while(result.next()) { // process results one row at a time
String eco = result.getString(1);
mapp2.put("ECO", eco);
String chktool = result.getString(2);
mapp2.put("CHECK_TOOL", chktool);
String lastchktime = result.getString(3);
mapp2.put("LAST_CHECK_TIME", lastchktime);
String status = result.getString(4);
mapp2.put("STATUS", status);
String statcmts = result.getString(5);
mapp2.put("STATUS_COMMENTS", statcmts);
String details = result.getString(6);
mapp2.put("DETAILS_FILE", details);
}
我在这里有2个问题: 1.有没有比使用result.getString()更好的方法了? 2.可以说,稍后将另一列添加到表中.我的代码有什么办法可以处理这个新添加的内容,而无需在那个时间点更改代码
I have 2 questions here: 1. Is there any better approach rather than using result.getString()??? 2. Lets say, another column gets added to the table at a later point. Is there any way my code handles this new addition without making change to the code at that point of time
推荐答案
您可以使用ResultSetMetaData
确定ResultSet
中列的数量和名称,并以此方式进行处理.但是请注意,更改数据库中的列数-影响您的代码-并使代码仍然有效可能并不总是一个好主意.
You can use ResultSetMetaData
to determine the number and names of the columns in your ResultSet
and deal with it this way. Note however that changing the number of columns in the database - affecting your code - and having the code still work may not always be a good idea.
此外,请注意,每次循环迭代时,您都将覆盖映射中的值.您可能想将这些地图添加到某种列表中?
Additionally, note that you're overwriting the values in your map on each iteration of the loop. You probably want to add those maps to some sort of List?
最后,您需要确保您的getString
方法不会在任何地方返回null
,否则将其放入地图中将引发异常.
Finally, you need to make sure that your getString
methods will not return null
anywhere, otherwise putting it into a map will throw an exception.
Statement select = conn.createStatement();
ResultSet result = select.executeQuery("SELECT * FROM D724933.ECOCHECKS WHERE ECO = '"+localeco+"' AND CHK_TOOL = '"+checknames[i]+"'");
ResultSetMetaData rsmd = result.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
List data = new ArrayList<Map>();
Map mapp2;
while(result.next()) { // process results one row at a time
mapp2 = new HashMap<String, String>();
for(int i=1; i<=numberOfColumns; i++) {
mapp2.put(rsmd.getColumnName(i), rs.getString(i));
}
data.add(mapp2);
}
这篇关于在迭代Java中的结果集时,比result.getString()更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!