1 package database;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.ResultSet;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8
9 /**
10 * <p>
11 * Description:JDBCUtils工具类
12 * </p>
13 *
14 * @author Administrator
15 * @date 2018年11月4日下午2:12:10
16 */
17 public class JDBCUtils {
18 public static final String DRIVER = "com.mysql.jdbc.Driver";
19 public static final String url = "jdbc:mysql://localhost:3306/jdbctest";
20 public static final String user = "root";
21 public static final String password = "root";
22 private static Connection conn;
23
24 static {
25 try {
26 Class.forName(DRIVER);
27 } catch (ClassNotFoundException e) {
28 System.out.println("数据库驱动注册失败!");
29 }
30 }
31
32 // 提供获取连接方法
33 public static Connection getConnection() throws SQLException {
34 // 获得连接
35 conn = DriverManager.getConnection(url, user, password);
36 // 返回连接
37 return conn;
38 }
39
40 // 关闭资源
41 public static void close(Connection conn, Statement stmt) {
42 if (stmt != null) {
43 try {
44 stmt.close();
45 } catch (SQLException e) {
46 e.printStackTrace();
47 }
48 }
49
50 if (conn != null) {
51 try {
52 conn.close();
53 } catch (SQLException e) {
54 e.printStackTrace();
55 }
56 }
57 }
58
59 // 关闭资源
60 public static void close(Connection conn, Statement stmt, ResultSet rs) {
61 if (rs != null) {
62 try {
63 rs.close();
64 } catch (SQLException e) {
65 e.printStackTrace();
66 }
67 }
68
69 if (stmt != null) {
70 try {
71 stmt.close();
72 } catch (SQLException e) {
73 e.printStackTrace();
74 }
75 }
76
77 if (conn != null) {
78 try {
79 conn.close();
80 } catch (SQLException e) {
81 e.printStackTrace();
82 }
83 }
84 }
85 }
![]()