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:@”);
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:@”); basicDataSource.setUsername(“user”);basicDataSource.setPassword(“password”); Connection connection=basicDataSource.getConnection();
结合JNDI的DataSource
以tomcat为例,将数据库驱动库复制到{tomcat}/commmon/lib目录下。
配置{tomcat}/conf/context.xml文件,加入:
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文件中,这样更便于打包部署。
Using a DataSourceUsing a DataSource
DataSource ds = null;
Connection conn = null;
ResultSet result = null;
Statement stmt = null;
ResultSetMetaData rsmd = null;
try{
Context context = newInitialContext();
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);
}
intcolumns=0;
try{
rsmd = result.getMetaData();
columns = rsmd.getColumnCount();
}
catch(SQLException e) {
System.out.println("Error occurred " + e);
}
%>
try{
for(inti=1; i<=columns; i++) {
out.write("
" + rsmd.getColumnLabel(i) + "");}
%>
while(result.next()) {
out.write("
");for(inti=1; i<=columns; i++) {
out.write("
" + result.getString(i) + "");}
out.write("
");}
// 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) {}
}
%>