标签:property connect 位置 动态 关闭 man close ring 连接
创建jdbc.properties
driver = com.mysql.jdbc.Driver url = jdbc:mysql://127.0.0.1:3306/db_one user = root password = root
创建工具类
package cn.itcast.util; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties; public class JDBCUtils { //连接数据库地址 private static String url; //用户名 private static String user; //用户密码 private static String password; //数据库版本 private static String driver; /** * 调用工具类启动注册 */ static { try { Properties pro = new Properties(); // 获取此类在src下绝对位置 ClassLoader classLoader = JDBCUtils.class.getClassLoader(); // 动态获取src下jdbc.properties的绝对地址 URL resource = classLoader.getResource("jdbc.properties"); // 将URL转换成String类型地址 String path = resource.getPath(); pro.load(new FileReader(path)); url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); try { Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } /** * 获取连接 * * @return 连接对象 * @throws SQLException sql异常 */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, user, password); } /** * 关闭资源 * * @param conn 连接对象 * @param stmt sql对象 */ public static void closeConnection(Connection conn, Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 关闭资源 * * @param conn 连接对象 * @param stmt sql对象 * @param rs 结果集对象 */ public static void closeConnection(Connection conn, Statement stmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } closeConnection(conn, stmt); } }
标签:property connect 位置 动态 关闭 man close ring 连接
原文地址:https://www.cnblogs.com/CN-Dragon/p/12971528.html