Using WebLogic JDBC in an Application

本文介绍如何在WebLogic环境中通过DataSource对象获取数据库连接。文章详细展示了从客户端应用程序使用DataSource对象来获得数据库连接的过程,并提供了注意事项以确保服务器端和客户端的JDBC驱动程序匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在工作中遇到一段代码,是和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; }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值