gpt4 book ai didi

java - JDBC executeQuery 无故显示错误

转载 作者:行者123 更新时间:2023-11-29 06:19:55 24 4
gpt4 key购买 nike

我正在使用 MySQL 编写一个简单的 JDBC 程序,但是只有一行代码出了什么问题。我没有看到任何错误,但下面提到的行在运行程序时显示错误

代码-

ResultSet recs = psmt.executeQuery("select * from item_master where catid = "+id1 +"and des = '" +sString+"';");

错误-

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'des = 'LG computer' ' at line 1

我还在 MySQL 中测试了这个查询并得到了输出 -

select * from item_master where catid = 2 and des = 'LG computer';

但是 Java 不允许我执行这一行。我也试过 LIKE

select * from item_master where catid = 2 and des LIKE 'LG computer';

最佳答案

您在 int 之后缺少一个空格,并且您不需要在查询中使用分号。类似的东西,

"select * from item_master where catid = "+id1 +" and des = '" +sString+"'"

String.format("select * from item_master where catid = %d and des = '%s'", 
id1, sString);

或者,我的偏好是使用PreparedStatement

String query = "select * from item_master where catid = ? and des = ?";
try (PreparedStatement ps = conn.prepareStatement(query)) {
ps.setInt(1, id1);
ps.setString(2, sString);
try (ResultSet rs = ps.executeQuery()) {
// ...
}
} catch (SQLException e) {
e.printStackTrace();
}

关于java - JDBC executeQuery 无故显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com