如何在 Java 中使用准备好的语句进行选择查询? [英] How to use prepared statement for select query in Java?

查看:23
本文介绍了如何在 Java 中使用准备好的语句进行选择查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾多次尝试使用准备好的语句,但它返回 SQL 异常.这是我的代码:

I had tried several times using prepared statements but it returns SQL exception. 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;
}

在运行时,我得到以下 SQL 异常:

While running this, I got the following SQL exception:

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.

推荐答案

您需要使用:

preparedStatement.executeQuery();

代替

preparedStatement.executeQuery(login);

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

when you pass in a string to executeQuery() that query is executed literally and thus the ? 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.

这篇关于如何在 Java 中使用准备好的语句进行选择查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆