package com.jdbc.utils; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class JDBCUtilsX { private static Properties properties=null; static{ properties=new Properties(); try { properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties")); } catch (IOException e) { e.printStackTrace(); } } /** * * @return Connection */ public static Connection getConnection(){ try { Class.forName(properties.getProperty("driver")); return DriverManager.getConnection(properties.getProperty("url"),properties.getProperty("user"),properties.getProperty("password")); } catch (Exception e) { e.printStackTrace(); return null; } } public static void close(AutoCloseable... autoCloseable){ for(AutoCloseable c:autoCloseable){ if(c!=null){ try { c.close(); } catch (Exception e) { e.printStackTrace(); } } } } }
db.properties文件的配置
url=jdbc:mysql://localhost:3306/test
user=root
password=123456
driver=com.mysql.jdbc.Driver