Java 无法从ResultSet获取值
我正在使用Java和MySQL开发一个web应用程序 我创建了一个方法,该方法应该根据数据库中的各种表返回相应列名的ArrayList 然而,当我调试该方法时,我意识到Java 无法从ResultSet获取值,java,mysql,jdbc,Java,Mysql,Jdbc,我正在使用Java和MySQL开发一个web应用程序 我创建了一个方法,该方法应该根据数据库中的各种表返回相应列名的ArrayList 然而,当我调试该方法时,我意识到而(rs.next())会导致错误。我用这个作为参考,因此我不确定哪里出了问题 这是代码。谢谢 // Returns the the all the columns in the table public ArrayList getColumnName(String tableName) throws SQLException {
而(rs.next())
会导致错误。我用这个作为参考,因此我不确定哪里出了问题
这是代码。谢谢
// Returns the the all the columns in the table
public ArrayList getColumnName(String tableName) throws SQLException {
ResultSet rs = null;
List<String> columnName = new ArrayList<String>();
Statement st = null;
Connection con = null;
try {
// Get a connection from the connection factory
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/information_schema", "root", "xxxx");
// Create a Statement object so we can submit SQL statements to the driver
st = con.createStatement();
StringBuilder sql = new StringBuilder("SELECT column_name FROM information_schema.columns " +
"WHERE table_schema = 'testDB' AND table_name = '");
sql.append(tableName).append("'");
rs = st.executeQuery(sql.toString());
while (rs.next()) { // getting error..
columnName.add(rs.getString("column_name"));
}
} catch (SQLException ex) {
Logger.getLogger(ModificationPage.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (con != null || st != null) {
st.close();
con.close();
}
}
return (ArrayList) columnName;
}
//返回表中的所有列
公共ArrayList getColumnName(String tableName)引发SQLException{
结果集rs=null;
List columnName=新建ArrayList();
语句st=null;
连接con=null;
试一试{
//从连接工厂获取连接
con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/information_schema“,”根“,”xxxx”);
//创建一个语句对象,这样我们就可以向驱动程序提交SQL语句
st=con.createStatement();
StringBuilder sql=new StringBuilder(“从信息\u schema.columns中选择列\u名称”+
“其中表_schema='testDB'和表_name='”;
append(tableName).append(“”);
rs=st.executeQuery(sql.toString());
而(rs.next()){//正在获取错误。。
columnName.add(rs.getString(“column_name”);
}
}catch(SQLException-ex){
Logger.getLogger(ModificationPage.class.getName()).log(Level.SEVERE,null,ex);
}最后{
如果(con!=null | | st!=null){
圣克洛斯();
con.close();
}
}
返回(ArrayList)列名称;
}
那么,这种异常永远不会发生
如果是这种情况,则应在rs=st.executeQuery(sql.toString())
处抛出一个查询错误,但如果它在期间到达,并且没有迭代,则是因为结果集为空
可能您向查询传递了错误的参数?根据(不确定您使用的是哪个版本的Java):
抛出:
SQLException-如果发生数据库访问错误或在关闭的结果集上调用此方法
如果您实际到达调用rs.next()的那一行,那么就不太可能发生数据库错误。因此,最有可能的结果是结果集已关闭
请将代码更改为以下内容,并查看是否仍在同一行中出现错误:
while (!rs.isClosed() && rs.next()) { // getting error..
columnName.add(rs.getString("column_name"));
}
还有,神圣的SQL注入攻击,蝙蝠侠
在执行操作时使用原始字符串并将其括在单引号内,会导致此代码存在SQL注入漏洞。基本上,恶意用户只需用一个引号(')结束您的查询,然后运行自己的查询。您看到的错误是什么?没有堆栈跟踪,发生的是从while(rs.next())开始,它将逐步捕获(SQLException ex)。同时,在我的web应用程序中,当应该显示的表组件不存在时,页面将刷新。非常感谢!它现在正在工作。我只是在做一个原型,所以现在可以用一个工作组件;)