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

数据库操作整合成一个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;
  }
}

标签:java,try,导包,static,catch,报错,null,conn,pstmt
来源: https://www.cnblogs.com/Gn9036/p/15004849.html