2015-02-24 128 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(查詢)