JDBC工具类


* 简化书写
* 分析
	* 注册驱动抽取
	* 抽取一个方法获取连接对象
		* 配置文件 jdbc.properties
			* url=
			* user=
			* password=
	* 释放资源
	package cn.icast.util;
	
	import java.io.FileReader;
	import java.io.IOException;
	import java.net.URL;
	import java.sql.*;
	import java.util.Properties;
	
	/*
	jdbc 工具类
	
	* */
	public class JDBCUtils {
	    private static String url;
	    private static String user;
	    private static String passworld;
	
	    static {
	        /*
	        * 读取资源文件
	        * */
	        try {
	            // 1
	            Properties pro = new Properties();
	            // 获取src 路径下的文件 ClassLoader
	            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
	            URL res = classLoader.getResource("jdbc.properties.properties");
	
	            String path = res.getPath();
	            // 加载文件
	            pro.load(new FileReader(path));
	            // 获取数据 赋值
	            String url = pro.getProperty("url");
	            String user = pro.getProperty("user");
	            String password = pro.getProperty("password");
	            String driver = pro.getProperty("driver");
	            // 注册驱动
	            Class.forName(driver);
	
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	        }
	    }
	
	    // 获取连接
	  
	    public static Connection getConnection () throws SQLException {
	        return DriverManager.getConnection(url,user,passworld);
	    }
	
	    public static void close (Statement stmt, Connection conn){
	        if(stmt != null){
	            try {
	                stmt.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if(conn != null){
	            try {
	                conn.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    public static void close (ResultSet res, Statement stmt, Connection conn){
	        if(res != null){
	            try {
	                res.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if(stmt != null){
	            try {
	                stmt.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	        if(conn != null){
	            try {
	                conn.close();
	            } catch (SQLException e) {
	                e.printStackTrace();
	            }
	        }
	
	    }
	}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
Last Updated: 8/4/2020, 6:23:45 PM