java當(dāng)中JDBC當(dāng)中請(qǐng)給出一個(gè)Oracle DataSource and SingleTon例子
Oracle DataSource and SingleTon:
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 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;
}
}
測(cè)試程序:
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 ");
}
}