[英]MySQL Java prepared statement Syntax error
I need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.我需要根据各种标准从 mysql 表中获取 select 行,例如颜色 = 黑色或尺寸 = L。
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.代码在没有准备好的语句和问号的情况下工作,但是每当我尝试使用问号时,代码都不会运行。
I have read something about typing the question mark like \'?'// but I am not sure about the exact format.我已经阅读了一些关于输入问号的内容,例如 \'?'//,但我不确定确切的格式。
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = con.createStatement();
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
ResultSet rs = stmt.executeQuery(sql);
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String此外,大小写成橙色,但当我只使用这个 sql 字符串时也会发生错误
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!我查看了 20 个不同的答案,但没有发现任何帮助,所以在此先感谢您的帮助!
You are executing the query using a normal java.sql.Statement
, not using a java.sql.PreparedStatement
.您正在使用普通
java.sql.Statement
执行查询,而不是使用java.sql.PreparedStatement
. This won't work because a normal Statement
does not support parameterized queries.这是行不通的,因为普通的
Statement
不支持参数化查询。 So, remove the creation and execution of the Statement
, and make sure you execute the statement using the PreparedStatement
:因此,删除
Statement
的创建和执行,并确保使用PreparedStatement
执行语句:
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement preparedStmt = con.prepareStatement(sql)) {
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
try (ResultSet rs = preparedStmt.executeQuery()) {
// process result set
}
}
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.还要注意添加了 try-with-resources,这将确保正确关闭连接、语句和结果集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.