Java & MySQL - 預處理語句



PreparedStatement 介面擴充套件了 Statement 介面,它為您提供了額外的功能,並且與通用 Statement 物件相比具有一些優勢。

此語句使您可以靈活地動態提供引數。

建立 PreparedStatement 物件

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

JDBC 中的所有引數都由符號表示,該符號稱為引數標記。在執行 SQL 語句之前,必須為每個引數提供值。

setXXX() 方法將值繫結到引數,其中XXX表示您希望繫結到輸入引數的值的 Java 資料型別。如果您忘記提供值,則會收到 SQLException。

每個引數標記都由其序數位置引用。第一個標記表示位置 1,下一個位置 2,依此類推。此方法與 Java 陣列索引不同,Java 陣列索引從 0 開始。

所有用於與資料庫互動的Statement 物件的方法(a)execute()、(b)executeQuery() 和(c)executeUpdate() 也適用於 PreparedStatement 物件。但是,這些方法已修改為使用可以輸入引數的 SQL 語句。

關閉 PreparedStatement 物件

就像您關閉 Statement 物件一樣,出於同樣的原因,您也應該關閉 PreparedStatement 物件。

只需簡單地呼叫 close() 方法即可完成此操作。如果您首先關閉 Connection 物件,它也會關閉 PreparedStatement 物件。但是,您應始終顯式關閉 PreparedStatement 物件以確保正確清理。

PreparedStatement pstmt = null;
try {
   String SQL = "Update Employees SET age = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   pstmt.close();
}

我們使用 try with resources,它自動處理資源關閉。以下示例演示了上述所有概念。

此程式碼是基於上一章中完成的環境和資料庫設定編寫的。

將以下示例複製並貼上到 TestApplication.java 中,編譯並執行如下所示:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestApplication {
   static final String DB_URL = "jdbc:mysql:///TUTORIALSPOINT";
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id, first, last, age FROM Employees";
   static final String UPDATE_QUERY = "UPDATE Employees set age=? WHERE id=?";

   public static void main(String[] args) {
      // Open a connection
      try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);
      ) {		      
         // Bind values into the parameters.
         stmt.setInt(1, 35);  // This would set age
         stmt.setInt(2, 102); // This would set ID

         // Let us update age of the record with ID = 102;
         int rows = stmt.executeUpdate();
         System.out.println("Rows impacted : " + rows );

         // Let us select all the records and display them.
         ResultSet rs = stmt.executeQuery(QUERY);		      

         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", First: " + rs.getString("first"));
            System.out.println(", Last: " + rs.getString("last"));
         }
         rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

現在讓我們編譯上述示例,如下所示:

C:\>javac TestApplication.java
C:\>

執行TestApplication時,會產生以下結果:

C:\>java TestApplication
Return value is : false
Rows impacted : 1
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mehnaz, Last: Fatma
ID: 102, Age: 35, First: Zaid, Last: Khan
ID: 103, Age: 30, First: Sumit, Last: Mittal
C:\>
廣告

© . All rights reserved.