我需要你帮助建立与weblogic dataSource的连接。在java bean的早期,我使用下面的代码建立与数据库的连接:
PreparedStatement ps = null;
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:oracle:thin:@xx.xx.xx.xx:1521:xxx", "hr", "hr123");
sql = " select * from employees";
ps = con.prepareStatement(sql);
}
catch (Exception e) {
System.err.print(e);
e.printStackTrace();
}
现在,我需要使用JNDI名称从weblogic数据源获取连接。我创建了dataSource,它被称为jdbc / HR,我尝试了下面的代码,但是我没有成功建立连接:
Context ctx = null;
Hashtable ht = new Hashtable();
java.sql.Connection conn = null;
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
try {
ctx = new InitialContext(ht);
javax.sql.DataSource ds =
(javax.sql.DataSource) ctx.lookup("demoDataSource");
conn = ds.getConnection();
}
答案 0 :(得分:0)
这解决了:
Connection con = null;
DataSource datasource = null;
Context initialContext = new InitialContext();
// "jdbc/MyDBname" >> is a JNDI Name of DataSource on weblogic
datasource = (DataSource) initialContext.lookup("jdbc/MyDBname");
con = datasource.getConnection();