【问题标题】:JDBC pass parameters to sql queryJDBC将参数传递给sql查询
【发布时间】:2015-04-25 13:13:59
【问题描述】:

我有

employee(id, name, company, salary);

需要显示给定 id 的数据

public static void Connect(String conString, String username, String password, int id) throws SQLException{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = null;
            conn = DriverManager.getConnection(conString, username, password);
            String query = "select * from employee where id = " + id + "" ;
            ResultSet rs = null;
            Statement stmt = null;
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);
            while(rs.next()){
                String name = rs.getString("name");
                String company = rs.getString("company");
                int salary = rs.getInt("salary");
                System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

但是这里我们直接传递 id。我们怎样才能像参数化查询一样传递它(比如我们如何在PreparedStatement 期间传递?

【问题讨论】:

标签: mysql jdbc


【解决方案1】:

在这种情况下,您的查询应该是

String query = "select * from employee where id = ?";

您需要创建 PreparedStatement 而不是 Statement

PreparedStatement preparedStatement = conn.prepareStatement(query);

然后将你的 id 设置为准备好的语句

preparedStatment.setInt(1, id);

最终执行查询

resultSet = preparedStatement.executeQuery();

【讨论】:

    【解决方案2】:

    这是旧帖子,但我仍然想添加我的答案。

    我没有足够的声誉来评论@prasad 的答案,所以我添加了小的更正作为单独的答案。实际上,在 praparedStatement.executeQuery() 中传递查询会抛出 MySQLSyntaxErrorException,因为它仍然调用 Statement.executeQuery 而不是 PreparedStatement.executeQuery()。我怎么知道?我不得不花费大量时间来解决这个问题。

    所以使用 PreparedStatement.executeQuery() 而不是 PreparedStament.executeQuery(query)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多