[英]How to establish database connection by using dataSource in Weblogic
在建立與weblogic數據源的連接時,我需要您的幫助。 在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();
}
解決方法是:
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.