Java JDBC

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 1 import com.mysql.jdbc.Connection;
 2 import com.mysql.jdbc.Statement;
 3 
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.net.URL;
 7 import java.sql.DriverManager;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.util.Properties;
11 
12 public class JDBCUtils {
13     private static String url;
14     private static String username;
15     private static String password;
16     private static String driver;
17 
18     static {
19         try {
20             Properties properties = new Properties();
21             ClassLoader classLoader = JDBCUtils.class.getClassLoader();
22             URL resource = classLoader.getResource("jdbc.properties");
23             String path = resource.getPath();
24             System.out.println(path);
25             properties.load(new FileReader(path));
26             url = properties.getProperty("url");
27             username = properties.getProperty("username");
28             password = properties.getProperty("password");
29             Class.forName(properties.getProperty("driver"));
30 
31         } catch (IOException | ClassNotFoundException e) {
32             e.printStackTrace();
33         }
34     }
35 
36     public static Connection getConnection() throws SQLException {
37 
38         return (Connection) DriverManager.getConnection(url, username, password);
39     }
40 
41     public static void closeConnection(Statement statement, Connection connection) {
42         if (null != statement) {
43             try {
44                 statement.close();
45             } catch (SQLException e) {
46                 e.printStackTrace();
47             }
48         }
49         if (null != connection) {
50             try {
51                 connection.close();
52             } catch (SQLException e) {
53                 e.printStackTrace();
54             }
55         }
56     }
57 
58     public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection) {
59         if (null != resultSet) {
60             try {
61                 resultSet.close();
62             } catch (SQLException e) {
63                 e.printStackTrace();
64             }
65         }
66         if (null != statement) {
67             try {
68                 statement.close();
69             } catch (SQLException e) {
70                 e.printStackTrace();
71             }
72         }
73         if (null != connection) {
74             try {
75                 connection.close();
76             } catch (SQLException e) {
77                 e.printStackTrace();
78             }
79         }
80     }
81 }
JDBCUtils

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-10-05 16:52  享受折腾  阅读(95)  评论(0编辑  收藏  举报