今天在工作中遇到一段代码,是和Weblogic有关的,利用它获取数据源
第一步:Getting a Database Connection from a DataSource Object
Obtaining a Client Connection Using a DataSource
注意事项: When using a JDBC connection in a client-side application, the exact same JDBC driver classes must be in the CLASSPATH on both the server and the client. If the driver classes do not match, you may see java.rmi.UnmarshalException exceptions.
//Importing Packages to Access DataSource Objects
import java.sql.*;
import java.util.*;
import javax.naming.*;
...
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,
"t3://hostname:port");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try ...{
ctx = new InitialContext(ht);
javax.sql.DataSource ds
= (javax.sql.DataSource) ctx.lookup ("myDataSource");
conn = ds.getConnection();
// You can now use the conn object to create
// Statements and retrieve result sets:
stmt = conn.createStatement();
stmt.execute("select * from someTable");
rs = stmt.getResultSet(); 
...
//Close JDBC objects as soon as possible
stmt.close();
stmt=null;
conn.close();
conn=null;
}
catch (Exception e) ...{
// a failure occurred
log message;
}
finally ...{ 
try ...{
ctx.close(); 
} catch (Exception e) ...{
log message; }
try ...{
if (rs != null) rs.close(); 
} catch (Exception e) ...{
log message; }
try ...{
if (stmt != null) stmt.close(); 
} catch (Exception e) ...{
log message; }
try ...{
if (conn != null) conn.close(); 
} catch (Exception e) ...{
log message; }
}
本文介绍如何在WebLogic环境中通过DataSource对象获取数据库连接。文章详细展示了从客户端应用程序使用DataSource对象来获得数据库连接的过程,并提供了注意事项以确保服务器端和客户端的JDBC驱动程序匹配。

被折叠的 条评论
为什么被折叠?



