1 package com.lt.grtg.util; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.PreparedStatement; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 import java.util.Properties; 11 12 public class DBUtil { 13 14 /** 15 * 连接URL 16 */ 17 private static String url; 18 /** 19 * 数据库连接用户名 20 */ 21 private static String username; 22 /** 23 * 数据库连接密码 24 */ 25 private static String password; 26 27 static{ 28 //加载数据库配置文件 29 InputStream inputStream = 30 DBUtil.class.getClassLoader().getResourceAsStream(properties文件路径); 31 Properties properties = new Properties(); 32 try { 33 properties.load(inputStream); 34 url = properties.getProperty("url"); 35 username = properties.getProperty("username"); 36 password = properties.getProperty("password"); 37 Class.forName(properties.getProperty("driver")); 38 } catch (IOException e) { 39 e.printStackTrace(); 40 throw new RuntimeException("加载db.properties文件失败"); 41 } catch (ClassNotFoundException e) { 42 e.printStackTrace(); 43 throw new RuntimeException("未找到db.properties文件中driver属性配置的数据库驱动文件"); 44 } 45 } 46 47 /** 48 * 获取数据库连接 49 * @return Connection 数据库连接 50 * @throws SQLException 数据库连接异常 51 */ 52 public static Connection getConnection() throws SQLException { 53 return DriverManager.getConnection(url, username, password); 54 } 55 56 /** 57 * 关闭数据库连接 58 * @param resultSet 结果集 59 * @param preparedStatement 60 * @param connection 数据库连接 61 */ 62 public static void closeConnection(ResultSet resultSet, 63 PreparedStatement preparedStatement,Connection connection){ 64 try { 65 //按顺序关闭JDBC对象:resultSet、preparedStatement、connection 66 if (resultSet != null) { 67 resultSet.close(); 68 } 69 if (preparedStatement != null) { 70 preparedStatement.close(); 71 } 72 if (connection != null) { 73 connection.close(); 74 } 75 } catch (SQLException e) { 76 e.printStackTrace(); 77 throw new RuntimeException("关闭数据库连接失败"); 78 } 79 } 80 81 }