JDBC PreparedStatement接口
时间:2020-01-09 10:35:20 来源:igfitidea点击:
在JDBC中使用Statement,我们可以在连接的数据库上执行SQL查询,但是使用Statement有一个限制,它没有给我们参数化SQL查询的机会,因此可以通过传递不同的参数来多次使用同一查询。在JDBC中有Statement的一个子接口,PreparedStatement,它提供了编写可多次执行的参数化查询的选项。
除了为我们提供编写动态查询的选项之外,使用JDBC PreparedStatement的另一个好处是。在PreparedStatement中,我们将在创建实例时传递该SQL语句,以便将SQL语句预先编译并存储在PreparedStatement对象中。然后可以使用该对象多次有效地执行该语句。由于在调用execute时查询已经被编译,因此PreparedStatement的性能更好。
如何获取PreparedStatement对象
我们可以通过调用Connection接口的prepareStatement(String sql)方法来获取PreparedStatement对象。例如
PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET DEPARTMENT = ? WHERE ID = ?");
这里的"?"是参数化语句中的占位符。这些占位符的值是通过setter方法提供的。
Java PreparedStatement中的方法
PreparedStatement接口的一些常用方法如下:
- execute()–在此PreparedStatement对象中执行SQL语句,它可以是任何类型的SQL语句。该方法返回一个布尔值;如果第一个结果是ResultSet对象,则为true;否则为false。如果是更新计数或者没有结果,则返回false。
- executeQuery()–在此PreparedStatement对象中执行SQL查询,并返回查询生成的ResultSet对象。
- executeUpdate()–在此PreparedStatement对象中执行SQL语句,该对象可以是DML语句,例如INSERT,UPDATE或者DELETE,也可以是不返回任何内容的SQL语句,例如SQL DDL语句(创建,删除)。
- addBatch()–向此PreparedStatement对象的一批命令中添加一组参数。
设置不同类型参数的值的设置方法也很多,在这里列出了其中一些
- setInt(int parameterIndex,int x)–将给定索引处的参数设置为给定Java int值。
- setLong(int parameterIndex,long x)–将给定索引处的参数设置为给定Java long值。
- setShort(int parameterIndex,short x)–将给定索引处的参数设置为给定Java short值。
- setString(int parameterIndex,String x)–将给定索引处的参数设置为给定Java String值。
- setDate(int parameterIndex,Date x)–使用运行应用程序的虚拟机的默认时区,将给定索引处的参数设置为给定java.sql.Date值。
- setTime(int parameterIndex,Time x)–将给定索引处的参数设置为给定java.sql.Time值。
- setTimestamp(int parameterIndex,Timestamp x)-将给定索引处的参数设置为给定java.sql.Timestamp值。
PreparedStatement Java示例
这是一个示例,显示JDBC PreparedStatement用于CRUD操作的用法。使用的数据库是MySql,模式是theitroad,使用的表是EMPLOYEE,其列分别为id,FIRST_NAME,LAST_NAME和DEPARTMENT,请注意,id是自动生成的,因此不会通过查询发送。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PreparedStatementDemo {
public static void main(String[] args) {
Connection connection = null;
try {
// Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
// connection object
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/theitroad",
"root", "admin");
// create Statement object
PreparedStatementDemo preparedStatement = new PreparedStatementDemo();
preparedStatement.insertEmployee(connection, "Ranjeet", "Sharma", "Police");
preparedStatement.updateEmployee(connection, 16, "Finance");
preparedStatement.deleteEmployee(connection, 22);
preparedStatement.getEmployeeById(connection, 16);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(connection != null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void insertEmployee(Connection connection, String fName, String lName, String dept) throws SQLException{
String insertSQL = "INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, DEPARTMENT) values (?, ?, ?)";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(insertSQL);
prepStmt.setString(1, fName);
prepStmt.setString(2, lName);
prepStmt.setString(3, dept);
int count = prepStmt.executeUpdate();
System.out.println("Number of records inserted- " + count);
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
private void updateEmployee(Connection connection, int id, String department) throws SQLException{
String updateSQL = "UPDATE EMPLOYEE SET DEPARTMENT = ? WHERE ID = ?";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(updateSQL);
prepStmt.setString(1, department);
prepStmt.setInt(2, id);
int count = prepStmt.executeUpdate();
System.out.println("Number of records updated " + count);
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
private void deleteEmployee(Connection connection, int id) throws SQLException {
String deleteSQL = "DELETE FROM EMPLOYEE WHERE id = ?";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(deleteSQL);
prepStmt.setInt(1, id);
int count = prepStmt.executeUpdate();
System.out.println("Number of records deleted " + count);
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
private void getEmployeeById(Connection connection, int id) throws SQLException{
String selectSQL = "SELECT * FROM EMPLOYEE WHERE id = ?";
PreparedStatement prepStmt = null;
try {
prepStmt = connection.prepareStatement(selectSQL);
prepStmt.setInt(1, id);
ResultSet rs = prepStmt.executeQuery();
while(rs.next()){
System.out.println("id: " + rs.getInt("id"));
System.out.println("First Name: " + rs.getString("FIRST_NAME"));
System.out.println("Last Name: " + rs.getString("LAST_NAME"));
System.out.println("Department: " + rs.getString("DEPARTMENT"));
}
}finally{
if(prepStmt != null){
prepStmt.close();
}
}
}
}

