//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);//查詢
+ 經過JDBC實現對數據庫記錄的增、刪、查、改。html
+ 如何高效利用好數據庫與服務器之間實現通訊的有限的數據庫鏈接資源?java
答案:JDBC+數據庫鏈接池。mysql
備註:sql
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層接口設計思想maven
經過此工具,操縱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)設計
[4] Dao層與鏈接池