如何在Java中使用预准备语句进行选择查询?

2022-09-03 00:05:25

我曾多次尝试使用预准备语句,但它返回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.

有什么建议可以做到这一点吗?任何一段代码都是值得赞赏的。


答案 1

您需要使用:

preparedStatement.executeQuery();

而不是

preparedStatement.executeQuery(login);

当您将字符串传递给该查询时该查询将按字面执行,因此被发送到数据库,然后创建错误。通过传递查询字符串,您不会执行为其传递值的“缓存”预准备语句。executeQuery()?


答案 2

对于您使用的这两个参数,因此第一个参数设置了两次。但您从未设置第二个参数的值。preparedStatement.setString(1, ..);

所以改变

preparedStatement.setString(1, mobile);
            preparedStatement.setString(1, password);

    preparedStatement.setString(1, mobile);
    preparedStatement.setString(2, password);

推荐