微信登录

JDBC - Statement - PreparedStatement - 7过程

不用Statement

方式 Statement PreparedStatement CallableStatement
原理 用于执行静态SQL语句并返回他所生成的对象 SQL语句被预编译并存储在此对象中,可以使用此对象多次高效地执行该语句。 用于执行SQL存储过程
不足 sql注入、无法操作Blob二进制大数据如图片 可操作Blob

sql注入: 因为sql语句是拼接字符串,所以会导致注释内如果填对了,就会导致登入成功

PreparedStatement(7个完全过程)

1.读取配置文件中的4个基本信息,连接数据库
2.加载驱动
3.获取连接
4.预编译sql语句,返回PreparedStatement的实例
5.填充占位符
6.执行操作
7.资源的关闭

  1. // 向customers表中添加一条记录
  2. @Test
  3. public void testInsert() {
  4. Connection conn = null;
  5. PreparedStatement ps = null;
  6. try {
  7. // 1.读取配置文件中的4个基本信息
  8. InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
  9. Properties pros = new Properties();
  10. pros.load(is);
  11. String user = pros.getProperty("user");
  12. String password = pros.getProperty("password");
  13. String url = pros.getProperty("url");
  14. String driverClass = pros.getProperty("driverClass");
  15. // 2.加载驱动
  16. Class.forName(driverClass);
  17. // 3.获取连接
  18. conn = DriverManager.getConnection(url, user, password);
  19. // System.out.println(conn);
  20. //4.预编译sql语句,返回PreparedStatement的实例
  21. String sql = "insert into customers(name,email,birth)values(?,?,?)";//?:占位符
  22. ps = conn.prepareStatement(sql);
  23. //5.填充占位符
  24. ps.setString(1, "哪吒");
  25. ps.setString(2, "nezha@gmail.com");
  26. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  27. java.util.Date date = sdf.parse("1000-01-01");
  28. ps.setDate(3, new Date(date.getTime()));
  29. //6.执行操作
  30. ps.execute();
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }finally{
  34. //7.资源的关闭
  35. try {
  36. if(ps != null)
  37. ps.close();
  38. } catch (SQLException e) {
  39. e.printStackTrace();
  40. }
  41. try {
  42. if(conn != null)
  43. conn.close();
  44. } catch (SQLException e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. }