用Java實現數據庫應用系統
|
我們在做信息系統的時候,都要訪問數據庫,我最近接手一個項目,項目組決定使用Java編寫,我負責數據層的設計和編碼,為了提高代碼的重用性和提高項目的開發效率。我們開發了一個通用的數據庫連接和完成基本操作的類庫,個人認為這個類在做MIS系統時還是有一定的價值,所以總結出來,介紹給大家。
連接工廠,實現了DataSource接口
package skydev.modules.data; import java.sql.*; import javax.sql.DataSource; import java.io.PrintWriter; public class ConnectionFactory implements DataSource { private String userName; private String password; private String driverName; private String url; private java.sql.Connection connection; /** * 根據設置的連接參數創建一個新的連接實例 * @return */ private Connection getNewConnection() { try { this.connection.close(); //試圖關閉連接 } finally { this.connection = null; //釋放連接 try { Class.forName(this.driverName); //加載驅動程序 //DriverManager.registerDriver(driver); try { this.connection = DriverManager.getConnection(this.url, this.userName, this.password); } catch (SQLException e) { throw e; } } finally { return this.connection; //返回新建立的連接 } } } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public java.sql.Connection getConnection() { if (connection != null) { try { if (connection.isClosed()) { connection = null; getNewConnection(); } } catch (SQLException ex) { } } if (connection == null) { //沒有設置連接則創建一個連接 getNewConnection(); } return connection; } public Connection getConnection(String userName, String password) throws SQLException { this.setUserName(userName); this.setPassword(password); return getConnection(); } public PrintWriter getLogWriter() { return null; } public void setLogWriter(PrintWriter printWriter) { } public void setLoginTimeout(int int0) { } public int getLoginTimeout() { return 0; } } |