如何在Java中使用预处理语句进行select查询?

jas*_*sim 12 java mysql sql jdbc prepared-statement

我曾多次尝试使用预处理语句,但它返回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;
}
Run Code Online (Sandbox Code Playgroud)

运行此时,我得到以下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.
Run Code Online (Sandbox Code Playgroud)

有什么建议使这项工作?任何一段代码都表示赞赏.

a_h*_*ame 26

你需要使用:

preparedStatement.executeQuery();
Run Code Online (Sandbox Code Playgroud)

代替

preparedStatement.executeQuery(login);
Run Code Online (Sandbox Code Playgroud)

当你传入一个字符串到executeQuery() 那个查询时,字面意思执行?,然后发送到数据库然后创建错误.通过传递查询字符串,您不会执行为其传递值的"缓存"预准备语句.