2015-02-24 125 views
1

JDBC参数传递给SQL查询

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

+0

[将参数传递给JDBC PreparedStatement]可能重复(http://stackoverflow.com/questions/12745186/passing-parameters-to-a-jdbc-preparedstatement) – 2015-02-24 09:53:46

回答

2
在这种情况下

查询应该是

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

,而不是声明你需要创建的PreparedStatement

PreparedStatement preparedStatement = conn.prepareStatement(query); 

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

preparedStatment.setInt(1, id); 

最后执行查询

resultSet = preparedStatement.executeQuery(); 
1

这是旧的文章,但我还是想加我的答案。

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

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