1、封装

  1. package com.glutnn.test;
  2. import java.sql.*;
  3. public class DBUtil {
  4. /**
  5. * 工具类中的构造方法是私有的
  6. * 因为工具类中的方法都是静态的,不需要new对象,直接采用类名调用即可
  7. */
  8. private DBUtil(){}
  9. /**
  10. * 静态代码块在类加载的时刻执行,并且只执行一次
  11. */
  12. static{
  13. try {
  14. Class.forName("com.mysql.jdbc.Driver");
  15. } catch (ClassNotFoundException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. /**
  20. * 获取数据库连接对象
  21. * @return 连接对象
  22. * @throws SQLException
  23. */
  24. public static Connection getConnection() throws SQLException {
  25. return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjprowernode","root","2000");
  26. }
  27. /**
  28. * 释放资源
  29. * @param conn 连接对象
  30. * @param ps 数据库操作对象
  31. * @param rs 结果集
  32. */
  33. public static void close(Connection conn , Statement ps , ResultSet rs){
  34. if (rs != null) {
  35. try {
  36. rs.close();
  37. } catch (SQLException throwables) {
  38. throwables.printStackTrace();
  39. }
  40. }
  41. if (ps != null) {
  42. try {
  43. ps.close();
  44. } catch (SQLException throwables) {
  45. throwables.printStackTrace();
  46. }
  47. }
  48. if (conn != null) {
  49. try {
  50. conn.close();
  51. } catch (SQLException throwables) {
  52. throwables.printStackTrace();
  53. }
  54. }
  55. }
  56. }

2、测试,模糊查询

  1. package com.glutnn.test;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. /**
  7. * 测试DBUtil
  8. * 写一个模糊查询
  9. */
  10. public class JDBCTest05 {
  11. public static void main(String[] args) {
  12. Connection conn = null;
  13. PreparedStatement ps = null;
  14. ResultSet rs = null;
  15. try {
  16. //获取连接
  17. conn = DBUtil.getConnection();
  18. //获取预编译的数据库操作对象
  19. String sql = "select ename from emp where ename like ?";
  20. ps = conn.prepareStatement(sql);
  21. ps.setString(1,"_A%");
  22. rs = ps.executeQuery();
  23. while (rs.next()){
  24. System.out.println(rs.getString("ename"));
  25. }
  26. } catch (SQLException throwables) {
  27. throwables.printStackTrace();
  28. } finally {
  29. //释放资源
  30. DBUtil.close(conn,ps,rs);
  31. }
  32. }
  33. }

3、悲观锁和乐观锁

1.png