国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

JAVA操作數據庫方式與設計模式應用

2019-11-18 11:36:42
字體:
來源:轉載
供稿:網友

1. 在業務層使用JDBC直接操作數據庫-最簡單,最直接的操作

1)數據庫url,username,passWord寫死在代碼中
Class.forName("Oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String password="tiger";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);

2)采用Facade和Command模式,使用DBUtil類封裝JDBC操作;
數據庫url,username,password可以放在配置文件中(如xml,PRoperties,ini等)。
這種方法在小程序中應用較多。

2.DAO(Data accessor Object)模式-松耦合的開始
DAO = data + accessor + domain object

例如User類-domain object (javabean)
UserDAO類-accessor ,提供的方法getUser(int id),save(User user)內包含了JDBC操作
在業務邏輯中使用這兩個類來完成數據操作。

使用Factory模式可以方便不同數據庫連接之間的移植。

3.數據庫資源治理模式
3.1 數據庫連接池技術
資源重用,避免頻繁創建,釋放連接引起大大量性能開銷;
更快的系統響應速度;

通過實現JDBC的部分資源對象接口( Connection, Statement, ResultSet ),可以使用Decorator設計模式分別產生三種邏輯資源對象: PooledConnection, PooledStatement和 PooledResultSet。


一個最簡單地數據庫連接池實現:
public class ConnectionPool {

private static Vector pools;
private final int POOL_MAXSIZE = 25;
/**
* 獲取數據庫連接
* 假如當前池中有可用連接,則將池中最后一個返回;若沒有,則創建一個新的返回
*/
public synchronized Connection getConnection() {
Connection conn = null;
if (pools == null) {
pools = new Vector();
}

if (pools.isEmpty()) {
conn = createConnection();
} else {
int last_idx = pools.size() - 1;
conn = (Connection) pools.get(last_idx);
pools.remove(last_idx);
}

return conn;
}

/**
* 將使用完畢的數據庫連接放回池中
* 若池中連接已經超過閾值,則關閉該連接;否則放回池中下次再使用
*/
public synchronized void releaseConnection(Connection conn) {
if (pools.size() >= POOL_MAXSIZE)
try {
conn.close();
} catch (SQLException e) {
// TODO自動生成 catch 塊
e.printStackTrace();
} else
pools.add(conn);
}

public static Connection createConnection() {
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
String user = "scott";
String password = "tiger";
conn = DriverManager.getConnection(url, user, password);
} catch (InstantiationException e) {
// TODO自動生成 catch 塊
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO自動生成 catch 塊
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO自動生成 catch 塊
e.printStackTrace();
} catch (SQLException e) {
// TODO自動生成 catch 塊
e.printStackTrace();
}
return conn;
}
}

注重:利用getConnection()方法得到的Connection,程序員很習慣地調用conn.close()方法關閉了數據庫連接,那么上述的數據庫連接機制便形同虛設。在調用conn.close()方法方法時如何調用releaseConnection()方法?這是要害。這里,我們使用Proxy模式和java反射機制。

public synchronized Connection getConnection() {
Connection conn = null;
if (pools == null) {
pools = new Vector();
}

if (pools.isEmpty()) {
conn = createConnection();
} else {
int last_idx = pools.size() - 1;
conn = (Connection) pools.get(last_idx);
pools.remove(last_idx);
}

ConnectionHandler handler=new ConnectionHandler(this);
return handler.bind(con);
}

public class ConnectionHandler implements InvocationHandler {
private Connection conn;
private ConnectionPool pool;

public ConnectionHandler(ConnectionPool pool){
this.pool=pool;
}

/**
* 將動態代理綁定到指定Connection
* @param conn
* @return
*/
public Connection bind(Connection conn){
this.conn=conn;
Connection proxyConn=(Connection)Proxy.newProxyInstance(
conn.getClass().getClassLoader(), conn.getClass().getInterfaces(),this);
return proxyConn;
}

/* (非 Javadoc)
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO自動生成方法存根
Object obj=null;
if("close".equals(method.getName())){
this.pool.releaseConnection(this.conn);
}
else{
obj=method.invoke(this.conn, args);
}

return obj;
}
}

在實際項目中,并不需要你來從頭開始來設計數據庫連接池機制,現在成熟的開源項目,如C3P0,dbcp,Proxool等提供了良好的實現。一般推薦使用Apache dbcp,基本使用實例:
DataSource ds = null;
try{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
ds = (DataSource)envCtx.lookup("jdbc/myoracle");
if(ds!=null){
out.println("Connection is OK!");
Connection cn=ds.getConnection();
if(cn!=null){
out.println("cn is Ok!");
Statement stmt = cn.createStatement();
ResultSet rst = stmt.executeQuery("select * from BOOK");
out.println("



發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 昌平区| 桐柏县| 项城市| 扎囊县| 盱眙县| 米泉市| 沧州市| 莎车县| 广南县| 尚志市| 离岛区| 济宁市| 绥芬河市| 遂昌县| 江山市| 渝中区| 茂名市| 河北省| 南召县| 通化县| 鄂伦春自治旗| 安新县| 杂多县| 缙云县| 林周县| 武邑县| 吉首市| 天水市| 海安县| 昭苏县| 平陆县| 吕梁市| 包头市| 松江区| 天津市| 凌云县| 珲春市| 和平县| 石首市| 白山市| 大丰市|