简介
具有预编译sql语句的能里
继承自 Statement 接口,由 preparedStatement方法创建。PreparedStatement具有预编译SQL语句能力,所以PreparedStatement 对象比 Statement 对象的效率更高,由于实现了动态的参数绑定,所以可以防止 SQL 注入,所以我们一般都使用 PreparedStatement。
PreparedStatement对象的特点:
- PreparedStatement 接口继承 Statement 接口
- PreparedStatement 效率高于 Statement
- PreparedStatement 支持动态绑定参数
- PreparedStatement 具备 SQL 语句预编译能力
- 使用 PreparedStatement 可防止出现 SQL 注入问题
PreparedStatement 的预编译能力
语句的执行步骤
- 语法和语义解析
- 优化 sql 语句,制定执行计划
- 执行并返回结果
但是很多情况,我们的一条 sql 语句可能会反复执行,或者每次执行的时候只有个别的值不同(比如 select 的 where 子句值不同,update 的 set 子句值不同,insert 的 values 值不同)。 如果每次都需要经过上面的词法语义解析、语句优化、制定执行计划等,则效率就明显不行 了。所谓预编译语句就是将这类语句中的值用占位符替代,可以视为将 sql 语句模板化或者说参数化预编译语句的优势在于:一次编译、多次运行,省去了解析优化等过程;此外预编译语 句能防止 sql 注入
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
public class PreparedStatementTest {
/**
* 添加用户
*/
public void insertUsers(String username,int userage){
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
//获取数据连接
connection =JDBCUtils.getConnection();
//定义sql语句
String sql = "insert into users values(default,?,?)";
//创建preparedStatement对象
preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
//完成参数的绑定
preparedStatement.setString(1,username);
preparedStatement.setInt(2,userage);
int i = preparedStatement.executeUpdate();
System.out.println(i);
}catch (Exception e){
e.printStackTrace();
}finally{
JDBCUtils.clossResource(preparedStatement,connection);
}
}
/**
* 根据用户id修改用户姓名、年龄
*/
public void updateUserById(int userid,String username,int userage){
Connection connection = null;
PreparedStatement preparedStatement = null;
try{
connection = JDBCUtils.getConnection();
preparedStatement = (PreparedStatement) connection.prepareStatement("update users set username = ?,userage= ? where userid=?");
preparedStatement.setString(1,username);
preparedStatement.setInt(2,userage);
preparedStatement.setInt(3,userid);
int i = preparedStatement.executeUpdate();
System.out.println(i);
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.clossResource(preparedStatement,connection);
}
}
/**
* 删除数据
*/
public void deleteUsersById(int userid){
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = (PreparedStatement) connection.prepareStatement("delete from users where userid=?");
preparedStatement.setInt(1,userid);
int i = preparedStatement.executeUpdate();
System.out.println(i);
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.clossResource(preparedStatement,connection);
}
}
}