JDBC工具类创建及使用

 1
 2 
 3 import java.io.FileInputStream;
 4 import java.sql.*;
 5 import java.util.Properties;
 6 
 7 /**
 8  * @author o_0sky
 9  * @date 2019/2/19 0:10
10  */
11 public class Jdbcutil {
12     static String driverName;
13     static String url;
14     static String user;
15     static String pwd;
16 
17     //不论外面调用多少次getConnection方法,驱动都只要注册一次
18     static {
19         try {
20             Properties p = new Properties();
21             p.load(new FileInputStream("jdbc.properties"));
22             //给参数赋值
23             driverName = p.getProperty("driverName");
24             url = p.getProperty("url");
25             user = p.getProperty("user");
26             pwd = p.getProperty("pwd");
27             Class.forName(driverName);
28         } catch (Exception e) {
29             e.printStackTrace();
30         }
31     }
32     //获取连接
33     public static Connection getConnection() throws SQLException {
34         Connection con = DriverManager.getConnection(url,user,pwd);
35         return con;
36     }
37     //释放资源
38     public static  void release(Connection con, Statement statement, ResultSet resultSet){
39         if (resultSet!=null){
40             try {
41                 resultSet.close();
42             } catch (SQLException e) {
43                 e.printStackTrace();
44             }
45         }
46         if (statement!=null){
47             try {
48                 statement.close();
49             } catch (SQLException e) {
50                 e.printStackTrace();
51             }
52         }
53         if (con!=null){
54             try {
55                 con.close();
56             } catch (SQLException e) {
57                 e.printStackTrace();
58             }
59         }
60     }
61 }

测试类:

 1 import java.sql.Connection;
 2 import java.sql.ResultSet;
 3 import java.sql.SQLException;
 4 import java.sql.Statement;
 5 
 6 /**
 7  * @author o_0sky
 8  * @date 2019/2/19 0:38
 9  */
10 public class Test {
11     public static void main(String[] args) throws SQLException {
12         //需要执行的Sql语句
13         String sql = "select * from tb_user";
14         //通过工具类获取连接
15         Connection con = Jdbcutil.getConnection();
16         Statement statement = con.createStatement();
17         //执行sql语句
18         ResultSet resultSet = statement.executeQuery(sql);
19         while (resultSet.next()) {
20             String name = resultSet.getString("name");
21             String age = resultSet.getString("age");
22         }
23         //释放资源
24         Jdbcutil.release(con, statement, resultSet);
25     }
26 }
原文地址:https://www.cnblogs.com/linsky/p/10398895.html