简介

具有预编译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 注入

  1. import com.mysql.jdbc.PreparedStatement;
  2. import java.sql.Connection;
  3. public class PreparedStatementTest {
  4. /**
  5. * 添加用户
  6. */
  7. public void insertUsers(String username,int userage){
  8. Connection connection = null;
  9. PreparedStatement preparedStatement = null;
  10. try{
  11. //获取数据连接
  12. connection =JDBCUtils.getConnection();
  13. //定义sql语句
  14. String sql = "insert into users values(default,?,?)";
  15. //创建preparedStatement对象
  16. preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
  17. //完成参数的绑定
  18. preparedStatement.setString(1,username);
  19. preparedStatement.setInt(2,userage);
  20. int i = preparedStatement.executeUpdate();
  21. System.out.println(i);
  22. }catch (Exception e){
  23. e.printStackTrace();
  24. }finally{
  25. JDBCUtils.clossResource(preparedStatement,connection);
  26. }
  27. }
  28. /**
  29. * 根据用户id修改用户姓名、年龄
  30. */
  31. public void updateUserById(int userid,String username,int userage){
  32. Connection connection = null;
  33. PreparedStatement preparedStatement = null;
  34. try{
  35. connection = JDBCUtils.getConnection();
  36. preparedStatement = (PreparedStatement) connection.prepareStatement("update users set username = ?,userage= ? where userid=?");
  37. preparedStatement.setString(1,username);
  38. preparedStatement.setInt(2,userage);
  39. preparedStatement.setInt(3,userid);
  40. int i = preparedStatement.executeUpdate();
  41. System.out.println(i);
  42. }catch (Exception e){
  43. e.printStackTrace();
  44. }finally {
  45. JDBCUtils.clossResource(preparedStatement,connection);
  46. }
  47. }
  48. /**
  49. * 删除数据
  50. */
  51. public void deleteUsersById(int userid){
  52. Connection connection = null;
  53. PreparedStatement preparedStatement = null;
  54. try {
  55. connection = JDBCUtils.getConnection();
  56. preparedStatement = (PreparedStatement) connection.prepareStatement("delete from users where userid=?");
  57. preparedStatement.setInt(1,userid);
  58. int i = preparedStatement.executeUpdate();
  59. System.out.println(i);
  60. }catch (Exception e){
  61. e.printStackTrace();
  62. }finally {
  63. JDBCUtils.clossResource(preparedStatement,connection);
  64. }
  65. }
  66. }