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

时间:2014-07-11 07:29:13

标签: 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;
}

运行此操作时,我得到以下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.

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

2 个答案:

答案 0 :(得分:24)

您需要使用:

preparedStatement.executeQuery();

而不是

preparedStatement.executeQuery(login);

当您将字符串传递给executeQuery() 时,查询按字面执行,因此?将发送到数据库,然后数据库会创建错误。通过传递查询字符串,您不会执行&#34;缓存&#34;您为其传递了值的预备声明。

答案 1 :(得分:1)

对于这两个参数,您使用preparedStatement.setString(1, ..);,因此第一个参数设置为两次。但你永远不会为第二个参数设置值。

所以改变

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

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