浏览 1677 次
锁定老帖子 主题:几种创建数据库链接的方式
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2008-09-01
最后修改:2009-07-13
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(); 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |