package com.web.study; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class ConnectionFactory { public static String driver; public static String dburl; public static String user; public static String password; public static final ConnectionFactory factory = new ConnectionFactory(); private Connection conn; static{ Properties prop = new Properties(); try { InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("dbconfig.properties"); prop.load(in); } catch (Exception e) { System.out.println("=====配置文件读取错误====="); } driver = prop.getProperty("driver"); dburl = prop.getProperty("dburl"); user = prop.getProperty("user"); password = prop.getProperty("password"); } private ConnectionFactory() { } public static ConnectionFactory getInstance() { return factory; } public Connection makeConnection() { try { Class.forName(driver); conn = DriverManager.getConnection(dburl,user,password); } catch (Exception e) { e.printStackTrace(); } return conn; } } package com.web.study; import java.sql.Connection; public class ConnectionFactoryTest { public static void main(String[] args) throws Exception { ConnectionFactory cf = ConnectionFactory.getInstance(); Connection conn = cf.makeConnection(); System.out.println(conn.getAutoCommit()); } }
时间: 2024-10-21 05:03:13