1、创建连接
1 package cc.whoisit; 2 3 import java.io.FileInputStream; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.util.Properties; 7 8 /** 9 * @author 10 * 读取数据库配置文件 11 */ 12 public class DBConnUtil { 13 private static Properties prop; 14 /** 15 * 配置文件名 16 */ 17 private static final String configureFileName = "config.properties"; 18 19 /** 20 * 获取数据库连接 21 * @param dbName 数据库名,与config.properties文件中的配置一至 22 * @return 数据库连接 23 * @throws Exception IOException, ClassNotFoundException, SQLException 24 */ 25 public static Connection getConnection(String dbName) throws Exception { 26 if(prop == null){ 27 prop = new Properties(); 28 prop.load(new FileInputStream(configureFileName)); 29 String dbDriver = prop.getProperty("dbDriver"); 30 Class.forName(dbDriver); 31 } 32 33 String url = prop.getProperty(dbName); 34 Connection conn = DriverManager.getConnection(url); 35 return conn; 36 } 37 }
2、连接工厂
1 package cc.whoisit; 2 3 import java.sql.Connection; 4 5 /** 6 * @author 7 * 数据库连接工厂 8 */ 9 public class DBFactory { 10 /** 11 * 获取测试库连接 12 * @return 数据库连接 13 * @throws Exception IOException, ClassNotFoundException,SQLException 14 */ 15 public static Connection getTestConnect() throws Exception { 16 Connection conn = DBConnUtil.getConnection("testDBRead"); 17 return conn; 18 } 19 }
3、配置文件
1 #Mysql 2 dbDriver=com.mysql.jdbc.Driver 3 testDBRead=jdbc:mysql://127.0.0.1:3306/test?user=root&password=&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
4、测试
1 package cc.whoisit; 2 3 import java.sql.Connection; 4 import java.sql.ResultSet; 5 import java.sql.Statement; 6 7 public class Test { 8 9 /** 10 * @param args 11 */ 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 try { 15 Connection conn = DBFactory.getTestConnect(); 16 String sql = "SELECT id, username, passwd FROM `user` LIMIT 100;"; 17 // statement用来执行SQL语句 18 Statement statement = conn.createStatement(); 19 ResultSet result = statement.executeQuery(sql); 20 while (result.next()) { 21 System.out.println("=========="); 22 System.out.println(result.getInt("id")); 23 System.out.println(result.getString("username")); 24 System.out.println(result.getString("passwd")); 25 } 26 27 if (!conn.isClosed()) { 28 conn.close(); 29 } 30 31 } catch (Exception e) { 32 // TODO: handle exception 33 e.printStackTrace(); 34 } 35 } 36 }
原文:http://www.cnblogs.com/Ehtan/p/4302426.html