DataSource接口(javax.sql.DataSource)替代DriverManager獲取Connection的方法,有以下好處:
- 可以在部署時靈活更換Connection實現;
- 可以更好的屏蔽數據庫的相關性。
以下以oracle爲例說明。
使用廠商DataSource
數據庫廠商在提高JDBC2.0和以上版本的JDBC驅動中應該包含廠商的DataSource實現。
OracleDataSource ods = new OracleDataSource();
ods.setUser(“my_user”);
ods.setPassword(“my_password”);
ods.setURL(“jdbc:oracle:thin:@<database>”);
Connection conn = ods.getConnection();
第三方DataSource
第三方廠商也可提供DataSource實現,比如免費開源的有DBCP,C3P0和proxool等,中間件廠商比如ibm的websphere,bea的weblogic等也都有實現。
以下是DBCP的示例:
BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(“oracle.jdbc.OracleDriver”); basicDataSource.setUrl(“jdbc:oracle:thin:@<database>”); basicDataSource.setUsername(“user”);basicDataSource.setPassword(“password”); Connection connection=basicDataSource.getConnection();
結合JNDI的DataSource
以tomcat爲例,將數據庫驅動庫複製到{tomcat}/commmon/lib目錄下。
配置{tomcat}/conf/context.xml文件,加入:
<Resource name=”jdbc/demo” auth=”Container” type=”javax.sql.DataSource”
driverClassName=”org.apache.derby.jdbc.ClientDriver”
url=”jdbc:derby://localhost:1527/demo”
username=”test”
password=”test”
maxActive=”2″
maxIdle=”1″
removeAbandoned=”true”
maxWait=”300″ />
在程序中訪問DataSource:
Context initContext = new InitialContext();
// 注意: 以下寫法只適用於tomcat(java:/comp/env).
Context envContext = (Context) initContext.lookup(“java:/comp/env”);
dataSource = (DataSource) envContext.lookup(“jdbc/demo”);
配置內容也可以加到webapp/META-INF/context.xml文件中,這樣更便於打包部署。
<%@page import="java.sql.*, javax.sql.*, javax.naming.*"%>
<html>
<head>
<title>Using a DataSource</title>
</head>
<body>
<h1>Using a DataSource</h1>
<%
DataSource ds = null;
Connection conn = null;
ResultSet result = null;
Statement stmt = null;
ResultSetMetaData rsmd = null;
try{
Context context = new InitialContext();
Context envCtx = (Context) context.lookup("java:comp/env");
ds = (DataSource)envCtx.lookup("jdbc/address");
if (ds != null) {
conn = ds.getConnection();
stmt = conn.createStatement();
result = stmt.executeQuery("SELECT * FROM AddressList");
}
}
catch (SQLException e) {
System.out.println("Error occurred " + e);
}
int columns=0;
try {
rsmd = result.getMetaData();
columns = rsmd.getColumnCount();
}
catch (SQLException e) {
System.out.println("Error occurred " + e);
}
%>
<table width="90%" border="1">
<tr>
<% // write out the header cells containing the column labels
try {
for (int i=1; i<=columns; i++) {
out.write("<th>" + rsmd.getColumnLabel(i) + "</th>");
}
%>
</tr>
<% // now write out one row for each entry in the database table
while (result.next()) {
out.write("<tr>");
for (int i=1; i<=columns; i++) {
out.write("<td>" + result.getString(i) + "</td>");
}
out.write("</tr>");
}
// close the connection, resultset, and the statement
result.close();
stmt.close();
conn.close();
} // end of the try block
catch (SQLException e) {
System.out.println("Error " + e);
}
// ensure everything is closed
finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {}
}
%>
</table>
</body>
</html>