多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
jdbc.properties ~~~ url=jdbc:mysql:///test user=root password= driver=com.mysql.jdbc.Driver ~~~ ~~~ package com.sn511.demo1; import java.io.FileReader; import java.net.URL; import java.sql.*; import java.util.Properties; public class JDBCUtils { private static String url; private static String username; private static String password; private static String driver; // 读取配置文件,只需要读取一次,使用静态代码块 static { try { // 1. 获取配置文件路径 ClassLoader classLoader = JDBCUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); //2. 创建Properties集合类 Properties properties = new Properties(); properties.load(new FileReader(path)); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); driver = properties.getProperty("driver"); //3.注册驱动 Class.forName(driver); }catch (Exception e){ e.printStackTrace(); } } /** * 获取连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } /** * 释放资源 * @param stmt * @param conn */ public static void close(Statement stmt, Connection conn){ if( stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if( conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * 释放资源 * @param rs * @param stmt * @param conn */ public static void close(ResultSet rs, Statement stmt, Connection conn){ if( rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if( stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if( conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } ~~~