简体   繁体   English

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

[英]How to use prepared statement for select query in Java?

I had tried several times using prepared statements but it returns SQL exception.我曾多次尝试使用准备好的语句,但它返回 SQL 异常。 here is my code:这是我的代码:

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;
}

While running this, I got the following SQL exception:运行此程序时,我收到以下 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.

Any suggestion to make this work?有什么建议可以使这项工作? any piece of code is appreciated.任何一段代码都值得赞赏。

You need to use:您需要使用:

preparedStatement.executeQuery();

instead of代替

preparedStatement.executeQuery(login);

when you pass in a string to executeQuery() that query is executed literally and thus the ?当您将字符串传递给executeQuery() ,该查询按字面执行,因此? is send to the database which then creates the error.发送到数据库,然后创建错误。 By passing query string you are not execution the "cached" prepared statement for which you passed the values.通过传递查询字符串,您不会执行为其传递值的“缓存”准备好的语句。

For both parameter you use preparedStatement.setString(1, ..);对于这两个参数,您使用preparedStatement.setString(1, ..); so the first parameter is set two times.所以第一个参数设置了两次。 but you never set the value for second parameter.但您从未设置第二个参数的值。

so change所以改变

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM