首页 文章

JDBC SQL异常:查询在MySQL提示符上正确执行,但在java中出错

提问于
浏览
2

我试图使用JDBC在MySQL数据库上运行以下SQL .

String selectQuery = "SELECT IFNULL(MAX(list_id), 0)+1 AS 'max_list_id' FROM UserHospitalLists WHERE user_id=?";

pStatement = connection.prepareStatement(selectQuery);
pStatement.setInt(1, 59);
ResultSet rs = pStatement.executeQuery(selectQuery);
while (rs.next()) {
     maxListId = rs.getString("max_list_id");
}

并得到以下错误 .

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在“?”附近使用正确的语法位于sun.reflect.NativeConstructorAccessorImpl.newInstance0(本地方法)的第1行,位于sun.reflect.NalConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57),位于java.lang的sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) . reflect.Constructor.newInstance(Constructor.java:525)

The query executes correctly on the MySQL prompt. What can be the problem ?

1 回答

  • 3

    这就是问题:

    ResultSet rs = pStatement.executeQuery(selectQuery);
    

    你正在使用 executeQuery 的错误重载 - 它是 Statement 声明的重载 . 你想要 PreparedStatement 引入的那个 . 您已经使用SQL准备了它,然后设置参数 - 您只需要:

    ResultSet rs = pStatement.executeQuery();
    

相关问题