標籤:
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, SQLException24 */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,SQLException14 */15 public static Connection getTestConnect() throws Exception {16 Connection conn = DBConnUtil.getConnection("testDBRead");17 return conn;18 }19 }
3、設定檔
1 #Mysql2 dbDriver=com.mysql.jdbc.Driver3 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 args11 */12 public static void main(String[] args) {13 // TODO Auto-generated method stub14 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 exception33 e.printStackTrace();34 }35 }36 }
java 資料庫連接工廠