2013-07-04 150 views
0

我正在使用Java和MySQL的Web应用程序工作。无法从ResultSet中获取值

我创建了一个方法,该方法应该根据数据库中的各个表返回各个列名的ArrayList。

但是,当我调试该方法时,我意识到while(rs.next())会导致错误。我用这个site作为参考,因此我不确定哪里出了问题。

这是代码。谢谢。

// 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; 
} 
+1

你看到什么错误? –

+0

没有堆栈跟踪,发生的事情是从while(rs.next())开始,它会逐步捕获(SQLException ex)。同时,在我的Web应用程序中,页面将刷新,而应该显示的表格组件不存在。 –

回答

1

按照Javadoc of 1.6(不知道的Java版本你正在使用):

抛出: SQLException - 如果发生数据库访问错误,或者调用此方法在已关闭的结果集

如果你真的到达了调用rs.next()的那一行,那么发生数据库错误就是,这是非常非常不可能的。所以,最可能的结果是结果集被关闭。

请改变你的代码下面,看看你仍然可以得到在同一行错误:

while (!rs.isClosed() && rs.next()) { // getting error.. 
     columnName.add(rs.getString("column_name")); 
} 

此外,圣SQL注入攻击,蝙蝠侠!

将原始字符串视为您正在做的事情并将其包含在单引号内导致此代码具有SQL注入漏洞。基本上,恶意用户所要做的就是用单引号(')结束查询,然后运行自己的查询。

+0

非常感谢!它正在工作。我只是在制作一个原型,所以一个工作组件现在可以完成;) –

0

因此,例外从未发生过?

查询误差应在rs = st.executeQuery(sql.toString())被抛出,如果是这样的话,但如果它做出while并没有重复,这是因为一个空结果

也许你传递错误的参数给的查询?