其他分享
首页 > 其他分享> > JDBC中工具类DBUtil

JDBC中工具类DBUtil

作者:互联网

 1 package com.ss.util;
 2 
 3 import java.sql.*;
 4 
 5 public class DBUtil {
 6 
 7     private static final String URL = "jdbc:mysql://127.0.0.1:3306/test2";
 8     private static final String user = "root";
 9     private static final String passwd = "root";
10 
11     static {
12         //1 加载驱动
13         try {
14             Class.forName("com.mysql.jdbc.Driver");
15         } catch (ClassNotFoundException e) {
16             e.printStackTrace();
17         }
18         System.out.println("123");
19     }
20 
21     public static Connection getConnect(){
22         //2 获取数据库连接
23         Connection connection = null;
24         try {
25             connection = DriverManager.getConnection(URL, user, passwd);
26         } catch (SQLException throwables) {
27             throwables.printStackTrace();
28         }
29         return connection;
30     }
31 
32     public static void close(PreparedStatement preparedStatement, Connection connection){
33         DBUtil.close(null,preparedStatement,connection);
34     }
35 
36     public static void close(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection){ //方法的重载
37         if (resultSet != null)
38         {
39             try {
40                 resultSet.close();
41             } catch (SQLException throwables) {
42                 throwables.printStackTrace();
43             }
44         }
45 
46         if (preparedStatement != null)
47         {
48             try {
49                 preparedStatement.close();
50             } catch (SQLException throwables) {
51                 throwables.printStackTrace();
52             }
53         }
54 
55         if (connection != null)
56         {
57             try {
58                 connection.close();
59             } catch (SQLException throwables) {
60                 throwables.printStackTrace();
61             }
62         }
63     }
64 }

 

标签:JDBC,throwables,try,connection,static,catch,close,工具,DBUtil
来源: https://www.cnblogs.com/hanfei123/p/14443890.html