我曾多次尝试使用准备好的语句,但它返回 SQL 异常。这是我的代码:
public ArrayList<String> name(String mobile, String password) {
ArrayList<String> getdata = new ArrayList<String>();
PreparedStatement stmt = null;
try {
String login = "select mobile, password from tbl_1 join tbl_2 on tbl_1.fk_id=2.Pk_ID where mobile=? and password=?";
String data = "select * from tbl_2 where password='" + password + "'";
PreparedStatement preparedStatement = conn.prepareStatement(login);
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
ResultSet rs = preparedStatement.executeQuery(login);
Statement stmts = (Statement) conn.createStatement();
if (rs.next()) {
System.out.println("Db inside RS");
ResultSet data = stmts.executeQuery(data);
while (data.next()) { /* looping through the resultset */
getdata.add(data.getString("name"));
getdata.add(data.getString("place"));
getdata.add(data.getString("age"));
getdata.add(data.getString("job"));
}
}
} catch (Exception e) {
System.out.println(e);
}
return getdata;
}
运行此程序时,我收到以下 SQL 异常:
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 '? and password=?' at line 1.
有什么建议可以让这项工作成功吗? 任何一段代码都会受到赞赏。
最佳答案
您需要使用:
preparedStatement.executeQuery();
而不是
preparedStatement.executeQuery(login);
当您将字符串传递给 executeQuery()
时,该查询将按字面意思执行,因此 ?
会发送到数据库,然后产生错误。通过传递查询字符串,您不会执行为其传递值的“缓存”准备语句。
关于java - 如何在Java中使用准备好的语句进行选择查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084707/