May 12

使用JDBC链接oracle报java.sql.SQLException: 无效的列索引: getValidColumnIndex的解决以及java.sql.ResultSetMetaData.getColumnLabel和getColumnName的区别学习 不指定

admin , 22:52 , 编程 » 编程(Java-Web) , 评论(0) , 引用(0) , 阅读(534) , Via 本站原创 | |
搜索
我已经获得阿里云幸运券,准备分享给您。请点击获取  
使用JDBC链接oracle报java.sql.SQLException: 无效的列索引: getValidColumnIndex的解决以及java.sql.ResultSetMetaData.getColumnLabel和getColumnName的区别学习
使用JDBC链接oracle报java.sql.SQLException: 无效的列索引: getValidColumnIndex的解决以及java.sql.ResultSetMetaData.getColumnLabelgetColumnName的区别学习
在搭建的项目中使用原来是通过如下方式把查询结果放到map里面的
Map<String, String> col_itlife365 = new HashMap<String, String>();
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++)
{
String title = rs.getMetaData().getColumnLabel(i);
col_itlife365.put(title, rs.getString(title));
}
row.add(col_itlife365);
报错了java.sql.SQLException: 无效的列索引: getValidColumnIndex,网上查询并学习了解后rs.getMetaData().getColumnLabel(i);中i是从1 开始算的,所以修改为如下
Map<String, String> col_itlife365 = new HashMap<String, String>();
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++)
{
String title = rs.getMetaData().getColumnLabel(i);
col_itlife365.put(title, rs.getString(title));
}
row.add(col_itlife365);
并学习了getColumnName和getColumnLabel两者都是索引从1开始,两者的区别如下:
getColumnName返回的是sql语句中field的原始名字
getColumnLabel是field的SQL AS的值。
比如如下的查询语句:
select
a.name as name
,a.description as description
,b.description as relatedDescription from a,b where ...
此时,getColumnName(3) == "description";而getColumnLabel(3) == "relatedDescription"
网上查询官网的API:

getColumnLabel
String getColumnLabel(int column)
throws SQLException
Gets the designated column's suggested title for use in printouts and displays. The suggested title is usually specified by the SQL AS clause. If a SQL AS is not specified, the value returned from getColumnLabel will be the same as the value returned by the getColumnName method.
Parameters:by www.itlife365.com
column - the first column is 1, the second is 2, ...
Returns:
the suggested column title
Throws:by www.itlife365.com
SQLException - if a database access error occurs
getColumnName
String getColumnName(int column)
throws SQLException
Get the designated column's name.
Parameters:

column - the first column is 1, the second is 2, ...
Returns:
column name
Throws:
SQLException - if a database access error occurs

这个也许和数据库也有关系。by www.itlife365.com
网友经测试,发现在SQLServer数据库中不存在这个问题,两种方法获取到的字段名是一致的。
为保险起见,建议使用getColumnLabel。
如果你想将ResultSet的结果映射到HashMap中,注意一定使用getColumnLabel,而不要用getColumnName,这样可提高程序的健壮性
the different between java.sql.ResultSetMetaData.getColumnLabel和getColumnName
the-different-jdbc-getColumnLabel-getColumnName-getValidColumnIndex
---end by itlife365.com