Java SE 之 數據庫操作工具類(DBUtil)設計


JDBC創建數據庫基本連接

//1.加載驅動程序
Class.forName(driveName);
//2.獲得數據庫連接
Connection connection = DriverManager.getConnection(dbResource,username,password);
//
String sql = "";
//3.獲得SQL處理語句
Statement statement = connection.createStatement();
PreparedStatement preparedStatement = connection.prepareStatement(sql); //更為安全
//4.獲得SQL執行結果intint
boolean result1 = statement.execute(sql); //執行
int result2 = statement.executeUpdate(sql); //執行更新
ResultSet resultSet = statement.executeQuery(sql);//查詢

DBUtil設計

關鍵問題

  + 通過JDBC實現對數據庫記錄的增、刪、查、改。

  + 如何高效利用好數據庫與服務器之間實現通信的有限的數據庫連接資源

    答案:JDBC+數據庫連接池

    備注:

      1.每創建一Connection類對象,就是占用一條連接資源。
      2.更佳的設計,可參考開源工具C3P0數據庫連接池解決方案。

ComboPooledDataSource pool = new ComboPooledDataSource(“demo”);
//pool.setUser("johnny");// (重新)設置用戶姓名
//pool.setPassword("123456");// 用戶密碼
//pool.setJdbcUrl("databaseUrl");// MySQL數據庫連接url
//pool.setDriverClass("com.mysql.jdbc.Driver");
//若是空參,自動到classpath目錄下面加載“c3p0-config.xml”配置文件,若是maven項目,則放置於/resources目錄下---配置文件的存儲位置和名稱必須是這樣,且使用“默認配置”
Connection con = pool.getConnection();
//連接關閉之后,內存會被釋放,下次取時會重新開(內存地址不共用)   

      另,推薦Apache開源工具Commons DBUtils:對JDBC進行簡單封裝的開源工具類庫,使用它能夠簡化JDBC應用程序的開發,同時也不會影響程序的性能。

  + 如何設計架構良好(可擴展性好、高內聚低耦合、代碼重用度高等DAO(Database Access Object)層

    答案:【IBaseDao + BaseDaoImpl】 + IBusinessDao + BusinessDaoImpl

    博文:Java SE 之 DAO層接口設計思想

設計方案

  通過此工具,操縱JDBC基礎層的連接和配置。

  依賴工具:Eclipse + mysql-connector-java-5.1.7-bin.jar + junit-4.12.jar[可選項]

//dbutil.properties
user:root
password:123456
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://127.0.0.1:3306/CorporationPropertyMS

//BDUtil.java


package com.cpms.test.junit;
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; /** * 數據庫操作工具類【通過配置文件dbutil.properties配置】 * * @author johnny zen * @since 2017-11-3 19:43 * * @param user * @param password * @param driver * @param url */ public class DBUtil{ private static String packagePath = "src.com.cpms.test.junit";//default current package's path private static Connection connection = null; private static Statement statement = null; private static Properties properties = null; private static String _propertiesFilePath = "dbutil.properties";//default properties file's path static{ // get current file's work path(notice:absolute path) String url = System.getProperty("user.dir") + "\\" + packagePath.replace(".", "\\") + "\\" + _propertiesFilePath; //open property file FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(url); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("[ DBUtil:ERROR ] "+ packagePath +" > open file failed!"); e.printStackTrace(); } properties = new Properties(); try { properties.load(fileInputStream); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("[ DBUtil:ERROR ] " + packagePath + " > load properties failed!"); e.printStackTrace(); } try { fileInputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("[DBUtil:ERROR ] " + packagePath + " > close file failed!"); e.printStackTrace(); } System.out.println("[DBUtil:SUCCESS ] " + packagePath + " > load properties success!"); } //init properties private static void initProperties(){ String driver = properties.getProperty("driver"); String url = properties.getProperty("url"); String user = properties.getProperty("user"); String password = properties.getProperty("passsword"); if((driver == null)||(url == null)||(user == null)||(password == null)){ System.out.println("[DBUtil:ERROR ] " + packagePath + " > arguments[url/user/password/driver]'s value is not complete."); } } //(lazy) load connection private static void loadConnection(){ //load Connection try{ Class.forName(properties.getProperty("driver")); }catch(ClassNotFoundException e){ System.out.println("[DBUtil:ERROR ] " + packagePath + " > load jdbc driver faild."); e.printStackTrace(); } //connection database try { connection = DriverManager.getConnection(properties.getProperty("url"), properties); } catch (SQLException e) { System.out.println("[DBUtil:ERROR ] " + packagePath + " > [loadConnection] connection database faild."); e.printStackTrace(); } System.out.println("[DBUtil:SUCCESS ] " + packagePath + " > [loadConnection] connection database success!"); } //get connection public static Connection getConnection(){ if(connection == null){ loadConnection(); } return connection; } //reset properties file path public static void setPropertiesFilePath(String propertiesFilePath){ _propertiesFilePath = propertiesFilePath; } //get dbutil's proprties public static Properties getProperties(){ return properties; } }

測試:

@Test
	public void  DBUtilTest() {
		Connection connection = DBUtil.getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		int index = 0;//resultSet's index
		String sql = "select * from employee";
		
		//init prepareStatement
		try {
			preparedStatement = connection.prepareStatement(sql);
		} catch (SQLException e) {
			System.out.println("[Test:execute error]: load prepareStatement failed!");
			e.printStackTrace();
		}
		
		//execute SQL:get resultSet
		try {
			
			resultSet = preparedStatement.executeQuery();
		} catch (SQLException e) {
			System.out.println("[Test:execute error]: execute sql failed!");
			e.printStackTrace();
		}
		
		
		try {
			while(resultSet.next()){
				//notice: resultSet.getObject(var):default: from 1 to n
				System.out.println("[Test] " + index + ":" + resultSet.getObject(index + 1).toString());
				index++;
			}
			System.out.println("[Test] row total is " + resultSet.getRow() + ".");
		} catch (SQLException e) {
			System.out.println("[Test:execute error]: iterate resultset failed!");
			e.printStackTrace();
		}
	
	}

  

 輸出:

[DBUtil:SUCCESS ] src.com.cpms.test.junit > load properties success!
[DBUtil:SUCCESS ] src.com.cpms.test.junit > [loadConnection] connection database success!
[Test] 0:employeeabcdefghijklmnopqrstvuwa
[Test] 1:department005abcdefghijklmnopqrs
[Test] 2:201611389
[Test] 3:畢雨蘭
[Test] 4:123456
[Test] 5:M
[Test] 6:19
[Test] 7:501928199205291867
[Test] 8:2012-08-10 08:23:59.0
[Test] 9:1
[Test] row total is 0.

 

推薦文獻

 [1] JDBC詳解

 [2] Java SE 之 數據庫操作工具類(DBUtil)設計

 [3] Java SE 之 DAO層接口設計思想

 [4] Dao層與連接池 

 [5] ComboPooledDataSource(C3P0連接池配置)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM