几种创建数据库链接的方式

1.采用jdbc方式
public static Connection getConnection() throws SQLException
{
Connection con = null;
try {
long beginTime = System.currentTimeMillis();
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
con = DriverManager.getConnection (url,username,password);
long endTime = System.currentTimeMillis();

} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
2.应用weblogic的JNDI方式
public Connection getConnection() throws Exception
{
Context initctx=null;
Context ctx=null;
DataSource ds=null;
Connection conn=null;
String aa="";
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001");
env.put(Context.SECURITY_PRINCIPAL,"weblogic");
env.put(Context.SECURITY_CREDENTIALS, "weblogic");
ctx = new InitialContext(env);
ds=(DataSource)ctx.lookup("jdbc/lmss");
conn = ds.getConnection();

log.info("=====dss=======" + ds);
if(ds==null) throw new Exception("no database");
} catch (Exception e) {
e.printStackTrace();
log.info("=======getConnection(aa) begin=====");
conn = getConnection(aa);
}
return conn;
}
3.应用websphere的JNDI方式
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"com.ibm.websphere.naming.WsnInitialContextFactory");
ht.put(Context.PROVIDER_URL, "iiop://127.0.0.1:2810");
Context ctx = new InitialContext(ht);
ds=(DataSource)ctx.lookup("jdbc/stock");
if(ds==null) throw new NamingException("no database");
con=ds.getConnection();

4.可以通过spring的配置文件获得datasource
ApplicationContext ctx=new FileSystemXmlApplicationContext("classpath:applicationContext-common.xml");
myDataSource = (DataSource) ctx.getBean("dataSource");
con = myDataSource.getConnection();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值