Để thực hiện truy vấn SELECT an toàn và hiệu quả trong Java, sử dụng PreparedStatement với phương thức executeQuery().
Cú pháp cơ bản
PreparedStatement pstmt = connection.prepareStatement(sql); ResultSet rs = pstmt.executeQuery();
Ví dụ hoàn chỉnh
Tạo bảng trong database sample:
mysql> CREATE TABLE JavaPreparedStatement (
-> Id INT,
-> Name VARCHAR(10),
-> Age INT
-> );
Chèn dữ liệu mẫu:
mysql> INSERT INTO JavaPreparedStatement VALUES(1, 'Larry', 23); mysql> INSERT INTO JavaPreparedStatement VALUES(2, 'Sam', 25); mysql> INSERT INTO JavaPreparedStatement VALUES(3, 'Mike', 26);
Mã Java sử dụng PreparedStatement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PreparedStatementSelectQueryDemo {
public static void main(String[] args) {
String JdbcURL = "jdbc:mysql://localhost:3306/sample?useSSL=false";
String Username = "root";
String password = "123456";
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rst = null;
String myQuery = "SELECT Id, Name, Age FROM JavaPreparedStatement";
try {
con = DriverManager.getConnection(JdbcURL, Username, password);
pstmt = con.prepareStatement(myQuery);
rst = pstmt.executeQuery();
System.out.println("Id\t\tName\t\tAge\n");
while (rst.next()) {
System.out.print(rst.getInt(1));
System.out.print("\t\t" + rst.getString(2));
System.out.print("\t\t" + rst.getInt(3));
System.out.println();
}
} catch (Exception exec) {
exec.printStackTrace();
} finally {
// Đóng tài nguyên theo thứ tự ngược lại
try { if (rst != null) rst.close(); } catch (Exception e) {}
try { if (pstmt != null) pstmt.close(); } catch (Exception e) {}
try { if (con != null) con.close(); } catch (Exception e) {}
}
}
}
Lợi ích của PreparedStatement:
- Ngăn chặn SQL Injection
- Tăng hiệu suất khi thực thi nhiều lần (query plan được cache)
- Xử lý tự động kiểu dữ liệu và escape ký tự đặc biệt