JDBC将参数传递给sql查询

时间:2015-02-24 01:46:57

标签: mysql jdbc

我有

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的方式)

2 个答案:

答案 0 :(得分:2)

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

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

而不是Statement,您需要创建PreparedStatement

PreparedStatement preparedStatement = conn.prepareStatement(query);

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

preparedStatment.setInt(1, id);

最后执行查询

resultSet = preparedStatement.executeQuery();

答案 1 :(得分:1)

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

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

所以使用 PreparedStatement.executeQuery()代替 PreparedStament.executeQuery(查询)