一,PreparedStatement介紹
- PreperedStatement是Statement的子類,它的實例對象可以通過Connection.preparedStatement()方法獲得,相對於Statement對象而言:PreperedStatement可以避免SQL注入的問題
- Statement會使數據庫頻繁編譯SQL,可能造成數據庫緩沖區溢出。PreparedStatement可對SQL進行預編譯,從而提高數據庫的執行效率。並且PreperedStatement對於sql中的參數,允許使用占位符的形式進行替換,簡化sql語句的編寫
二,使用PreparedStatement對象完成對數據庫的CRUD操作
注意:編寫測試代碼時要提前搭建好實驗環境我的試驗環境已經在我的博客【JDBC(二)---使用JDBC對數據庫進行CRUD】中搭建完畢
測試代碼
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DemoTest1 {
@Test //插入
public void insert(){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
//獲取一個數據庫連接
connection= Demo.getConnection();
//要執行的SQL命令,SQL中的參數使用?作為占位符
String sql="insert into abc(id,name,password) values(?,?,?)";
//通過conn對象獲取負責執行SQL命令的prepareStatement對象
preparedStatement = connection.prepareStatement(sql);
//為SQL語句中的參數賦值
preparedStatement.setInt(1,1);//插入id=1
preparedStatement.setString(2,"鋼鐵俠");//插入name=鋼鐵俠
preparedStatement.setString(3,"123");//插入password=123
//執行插入操作,executeUpdate方法返回成功的條數
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功!!!");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
Demo.release(connection,preparedStatement,null);
}
}
@Test //刪除
public void delete(){
Connection connection=null;
PreparedStatement preparedStatement=null;
try {
connection = Demo.getConnection();
//當id=?時 刪除這一行
String sql="delete from abc where id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("刪除成功!!!");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
Demo.release(connection,preparedStatement,null);
}
}
@Test //更新
public void update(){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
connection= Demo.getConnection();
//當id=?時 更新name和password的數據
String sql="update abc set name=?,password=? where id=?";
preparedStatement= connection.prepareStatement(sql);
preparedStatement.setString(1,"蜘蛛俠");
preparedStatement.setString(2,"567");
preparedStatement.setInt(3,1);
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("更新成功");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
Demo.release(connection,preparedStatement,null);
}
}
@Test //查找
public void find(){
Connection connection=null;
PreparedStatement preparedStatement=null;
ResultSet resultSet=null;
try {
connection= Demo.getConnection();
//當id=?時 查詢這個一列
String sql="select * from abc where id=?";
preparedStatement= connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
//查詢這一列的name
System.out.println(resultSet.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
Demo.release(connection,preparedStatement,resultSet);
}
}
}