无法从ResultSet获取值

时间:2013-07-04 03:09:51

标签: java mysql jdbc

我正在使用Java和MySQL开发Web应用程序。

我创建了一个方法,该方法应该根据数据库中的各个表返回相应列名的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;
}

2 个答案:

答案 0 :(得分:1)

根据Javadoc of 1.6(不确定您使用的Java版本):

  

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

如果你真的到了调用rs.next()的行,那么非常非常不可能发生数据库错误然后。因此,最可能的结果是结果集已关闭。

请将您的代码更改为以下内容,看看您是否仍然在同一行上收到错误:

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

另外,神圣的SQL注入攻击,蝙蝠侠!

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

答案 1 :(得分:0)

那么,异常永远不会发生?

如果是这种情况,应该在rs = st.executeQuery(sql.toString())抛出一个查询错误,但是如果它转到while并且没有迭代,则是因为结果集为空

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

相关问题