1 public class DBUtil {
 2   private static final String DBDRIVER = "com.mysql.jdbc.Driver";
 3 
 4   //注意这里的数据库名需要修改成你自己操作的数据库
 5   private static final String DBURL = "jdbc:mysql://localhost:3306/movie?serverTimezone=GMT%2B8" +
 6     "&characterEncoding=utf8&useUnicode=true&useSSl=false";
 7   private static final String DBUSER = "root";
 8   private static final String DBPASSWORD = "root";
 9 
10 
11   //获取数据库连接对象
12   public static Connection getConnection() {
13     Connection conn = null;
14     try {
15       Class.forName(DBDRIVER);
16       conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
17     } catch (Exception e) {
18       e.printStackTrace();
19     }
20     return conn;
21   }
22 
23   //关闭资源连接
24   public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
25     if(rs != null) {
26       try {
27         rs.close();
28       } catch (Exception e) {
29         // TODO Auto-generated catch block
30         e.printStackTrace();
31       }
32     }
33     if(stmt != null) {
34       try {
35         stmt.close();
36       } catch (Exception e) {
37         // TODO Auto-generated catch block
38         e.printStackTrace();
39       }
40     }
41     if(conn != null) {
42       try {
43         conn.close();
44       } catch (Exception e) {
45         // TODO Auto-generated catch block
46         e.printStackTrace();
47       }
48     }
49   }
50 
51   //创建数据库操作对象(PreparedStatement对象)
52   public static PreparedStatement getPreparedStatement(Connection conn, String sql) {
53     PreparedStatement pstmt = null;
54     try {
55       pstmt = conn.prepareStatement(sql);
56     } catch (Exception e) {
57       e.printStackTrace();
58     }
59     return pstmt;
60   }
61 
62   //创建数据库操作对象(Statement对象)
63   public static Statement getStatement(Connection conn) {
64     Statement stmt = null;
65     try {
66       stmt = conn.createStatement();
67     } catch (Exception e) {
68       e.printStackTrace();
69     }
70     return stmt;
71   }
72 
73 
74   //封装更新操作语句
75   public static int executeDML(String sql, Object...objs) {
76     int rows = 0;
77     Connection conn = null;
78     PreparedStatement pstmt = null;
79     try {
80       conn = getConnection();
81       pstmt = getPreparedStatement(conn, sql);
82       for (int i = 0; i < objs.length; i++) {
83         pstmt.setObject(i + 1, objs[i]);
84       }
85       rows = pstmt.executeUpdate();
86     } catch (Exception e) {
87       e.printStackTrace();
88     } finally {
89       closeAll(null, pstmt, conn);
90     }
91     return rows;
92   }
93 }