ConnectionFactory 类
package com.oaec.shopping.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class ConnectionFactory { private static String DRIVER; private static String URL; private static String UNAME; private static String UPASS; // 在类被加载时执行,只会执行一次 static { // 从配置文件读取键值对 // 存储键值对--集合 Properties prop = new Properties(); try { // 把properties文件中的数据加载到prop对象中 // 要求:ConnectionFactory类和jdbc.properties在同一个包下 prop.load(ConnectionFactory.class.getResourceAsStream("jdbc.properties")); // value=getProperty(key):通过键获取值 DRIVER = prop.getProperty("driver"); URL = prop.getProperty("url"); UNAME = prop.getProperty("username"); UPASS = prop.getProperty("password"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection() { Connection conn = null; try { Class.forName(DRIVER); conn = DriverManager.getConnection(URL, UNAME, UPASS); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void main(String[] args) { System.out.println(ConnectionFactory.getConnection()); } } jdbc.properties文件 driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ye_mart?useUnicode=true&characterEncoding=utf-8 username=root password=