数据库操作整合成一个DBUtil,去除重复代码(如果报错,注意导包,导包应该导的是java.sql下的包)

2021/7/13 19:12:57

本文主要是介绍数据库操作整合成一个DBUtil,去除重复代码(如果报错,注意导包,导包应该导的是java.sql下的包),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

public class DBUtil {
  private static final String DBDRIVER = "com.mysql.jdbc.Driver";

  //注意这里的数据库名需要修改成你自己操作的数据库
  private static final String DBURL = "jdbc:mysql://localhost:3306/movie?serverTimezone=GMT%2B8" +
    "&characterEncoding=utf8&useUnicode=true&useSSl=false";
  private static final String DBUSER = "root";
  private static final String DBPASSWORD = "root";


  //获取数据库连接对象
  public static Connection getConnection() {
    Connection conn = null;
    try {
      Class.forName(DBDRIVER);
      conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return conn;
  }

  //关闭资源连接
  public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
    if(rs != null) {
      try {
        rs.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    if(stmt != null) {
      try {
        stmt.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    if(conn != null) {
      try {
        conn.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

  //创建数据库操作对象(PreparedStatement对象)
  public static PreparedStatement getPreparedStatement(Connection conn, String sql) {
    PreparedStatement pstmt = null;
    try {
      pstmt = conn.prepareStatement(sql);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return pstmt;
  }

  //创建数据库操作对象(Statement对象)
  public static Statement getStatement(Connection conn) {
    Statement stmt = null;
    try {
      stmt = conn.createStatement();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return stmt;
  }


  //封装更新操作语句
  public static int executeDML(String sql, Object...objs) {
    int rows = 0;
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = getConnection();
      pstmt = getPreparedStatement(conn, sql);
      for (int i = 0; i < objs.length; i++) {
        pstmt.setObject(i + 1, objs[i]);
      }
      rows = pstmt.executeUpdate();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      closeAll(null, pstmt, conn);
    }
    return rows;
  }
}



这篇关于数据库操作整合成一个DBUtil,去除重复代码(如果报错,注意导包,导包应该导的是java.sql下的包)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程