java.sql.SQLException:无法使用executeQuery()发出数据操作语句

时间:2014-05-05 17:08:38

标签: java mysql sql jdbc

我似乎无法解决这个问题。我需要ResultSet来获取实际的Object。错误是:java.sql.SQLException: Can not issue data manipulation statements with executeQuery().位于rs = pst.executeQuery();。代码:

Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;

String url = null; //Set, but not visible in code.
String user = null; //Set, but not visible in code.
String password = null; //Set, but not visible in code.

public Object get(String table, String key){
    try {
        con = DriverManager.getConnection(url, user, password);

        String query = "SELECT * FROM `" + table + "` WHERE key = ?;";
        pst = con.prepareStatement(query);

        pst.setString(1, key);
        pst.executeUpdate();

        rs = pst.executeQuery();

        rs.next();

        return rs.getObject(1);

    } catch (SQLException ex) {

        return null;

    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pst != null) {
                pst.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {

            return null;

        }
    }
}

1 个答案:

答案 0 :(得分:0)

不要使用executeQuery使用你的sql语句所使用的executeUpdate 之间(更新,插入,删除)请参阅 https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)