Using WebLogic JDBC in an Application
今天在工作中遇到一段代码,是和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.
//ImportingPackagestoAccessDataSourceObjects
importjava.sql.*;
importjava.util.*;
importjavax.naming.*;
...
Contextctx=null;
Hashtableht=newHashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,
"t3://hostname:port");
Connectionconn=null;
Statementstmt=null;
ResultSetrs=null;
try...{
ctx=newInitialContext(ht);
javax.sql.DataSourceds
=(javax.sql.DataSource)ctx.lookup("myDataSource");
conn=ds.getConnection();
//Youcannowusetheconnobjecttocreate
//Statementsandretrieveresultsets:
stmt=conn.createStatement();
stmt.execute("select*fromsomeTable");
rs=stmt.getResultSet();
...
//CloseJDBCobjectsassoonaspossible
stmt.close();
stmt=null;
conn.close();
conn=null;
}
catch(Exceptione)...{
//afailureoccurred
logmessage;
}
finally...{
try...{
ctx.close();
}catch(Exceptione)...{
logmessage;}
try...{
if(rs!=null)rs.close();
}catch(Exceptione)...{
logmessage;}
try...{
if(stmt!=null)stmt.close();
}catch(Exceptione)...{
logmessage;}
try...{
if(conn!=null)conn.close();
}catch(Exceptione)...{
logmessage;}
}
页:
[1]