随笔 - 40, 文章 - 0, 评论 - 20, 引用 - 0
数据加载中……

通过weblogic的数据源获得数据库连接的方法

通过weblogic的数据源获得数据库连接的方法:

package com.moonsoft.datasource;

import javax.naming.NamingException;
import java.util.Hashtable;
import javax.naming.InitialContext;
import java.sql.Connection;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class TestDataSource {

  public static String WEB_URL = "t3://localhost:9000";
  public static String DATA_SOURCE = "JDBCDS";
  public static String weblogic_context_factory =
      "weblogic.jndi.WLInitialContextFactory";
  public TestDataSource() {
  }
  public static Object lookUp() throws NamingException {
    Hashtable env = new Hashtable();
    env.put(InitialContext.INITIAL_CONTEXT_FACTORY, weblogic_context_factory);
    env.put(InitialContext.PROVIDER_URL, WEB_URL);
    InitialContext tempContext = new InitialContext(env);
    return tempContext.lookup(DATA_SOURCE);
  }
  public static Connection getConnection() throws SQLException {
    Connection conn = null;
    try {
      DataSource ds = (DataSource) lookUp();
      if (ds == null) {
        throw new SQLException("查询到空数据源!");
      }
      conn = ds.getConnection();
    }
    catch (NamingException ex) {
      ex.printStackTrace();
    }
    return conn;
  }
  public static void releaseConnection(Connection conn, PreparedStatement sta,
                                       ResultSet rs) {
    try {
      if (rs != null) {
        rs.close();
      }
      if (sta != null)
        sta.close();
      if (conn != null)
        conn.close();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public static void testSearch() {
    Connection conn = null;
    PreparedStatement sta = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      String sql = "select * from admin_config where config_name like ?";
      sta = conn.prepareStatement(sql);
      sta.setString(1,"%Sms%");
      rs = sta.executeQuery();
      if (rs != null) {
        while (rs.next()) {
          System.out.println(rs.getString(1));
        }
      }
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    finally {
      releaseConnection(conn,sta,rs);
    }
  }
  public static void main(String [] argv){
    testSearch();
  }
}

posted on 2006-01-05 10:51 月亮 阅读(1236) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: