当前位置:Gxlcms > 数据库问题 > JDBC建立/关闭数据库连接

JDBC建立/关闭数据库连接

时间:2021-07-01 10:21:17 帮助过:3人阅读

driverClass = com.mysql.jdbc.Driver //这一句代表数据库驱动类的全类名 2 jdbcUrl = jdbc:mysql://localhost:3306/test //这一句是配置需要访问的数据库,test是数据库名 3 user = root 4 password = 123

建立数据库连接和关闭连接的工具类jdbcTools

 1 public class jdbcTools {
 2 
 3     //获取数据库连接
 4     public static Connection getConnection() throws Exception {
 5         Connection connection = null;
 6         String driverClass = null;
 7         String url = null;
 8         String user = null;
 9         String password = null;
10 
11         InputStream in = jdbcTools.class.getClassLoader().getResourceAsStream("jdbc.properties");//加载配置文件
12         Properties properties = new Properties();
13         properties.load(in);
14 
15         driverClass = properties.getProperty("driverClass");
16         url = properties.getProperty("jdbcUrl");
17         user = properties.getProperty("user");
18         password = properties.getProperty("password");
19 
20         Class.forName(driverClass);//通过全类名加载驱动类
21         connection = DriverManager.getConnection(url,user,password);//DriverManager可以实现对各个数据库驱动类的同一管理,并获取数据库的连接
22 
23         return connection;
24 
25     }
26 
27     //关闭资源
28     public static void releaseResource(Statement statement,Connection connection){
29         if(statement != null){
30             try{
31                 statement.close();
32             }catch (Exception e){
33                 e.printStackTrace();
34             }
35         }
36         if(connection != null){
37             try{
38                 connection.close();
39             }catch (Exception e1){
40                 e1.printStackTrace();
41             }
42         }
43     }
44 
45     public static void releaseResource(ResultSet resultSet,Statement statement, Connection connection){
46 
47         if(resultSet != null){
48             try{
49                 resultSet.close();
50             }catch (Exception e){
51                 e.printStackTrace();
52             }
53         }
54         if(statement != null){
55             try{
56                 statement.close();
57             }catch (Exception e){
58                 e.printStackTrace();
59             }
60         }
61         if(connection != null){
62             try{
63                 connection.close();
64             }catch (Exception e1){
65                 e1.printStackTrace();
66             }
67         }
68     }

 

JDBC建立/关闭数据库连接

标签:

人气教程排行