java当中JDBC当中请给出一个Oracle DataSource and SingleTon例子
Oracle DataSource and SingleTon:
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
import oracle.jdbc.pool.OracleDataSource;
import java.sql.Connection;
import java.sql.*;
public class OracleSingletonDataSource {
static private OracleDataSource ods;
private OracleSingletonDataSource() {
try{
ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:@localhost:1521:qixy");
ods.setUser("scott");
ods.setPassword("tiger");
}catch(Exception e){
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
if (ods==null)
{
new OracleSingletonDataSource();
// ods.getConnection();
}
Connection con =null;
try {
con = ods.getConnection();
} catch (SQLException ex) {
ex.printStackTrace();
}
return con;
}
}
测试程序:
import java.sql.*;
public class testOracleSingletonDataSource {
public static void main(String args[]) {
Connection con;
Statement stm = null;
ResultSet rs = null;
try {
/* DatabaseConnection's "static private OracleDataSource ods;" is always in the memory once it is created becasue it is static..*/
con = OracleSingletonDataSource.getConnection();
stm = con.createStatement();
rs = stm.executeQuery("select ename from emp");
while(rs.next())
{
String name=rs.getString("ename");
System.out.println(name);
}
rs.close();
stm.close();
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
// System.out.println("the following is the second time ");
}
}