小编典典

如何在Java中将准备好的语句用于选择查询?

mysql

我已经使用预备语句尝试了几次,但是它返回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.

有什么建议可以使这项工作吗?任何代码都值得赞赏。


阅读 307

收藏
2020-05-17

共1个答案

小编典典

您需要使用:

preparedStatement.executeQuery();

代替

preparedStatement.executeQuery(login);

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

2020-05-17