import java.sql.*;
import java.util.*;
import javax.naming.*;
import javax.sql.DataSource;

public class SqlAccess {

    //数据库连接
    public Connection conn = null;
    //结果集
    private ResultSet rs = null;
    //数据库访问段
    public Statement stmt = null;
    //是否连接数据库
    private boolean isConnDB = false;
    private boolean isDefault = true;
    private String newDSName = null;
    public static HashMap logmap = new HashMap();
    public static int begincont = 0;
    private int count = 0;
    public String serverType="";
    public String jndiName = "";

    public static final String WLS_INITIAL_CONTEXT_FACTORY =  "weblogic.jndi.WLInitialContextFactory";
    public static final String TBJBOSS_INITIAL_CONTEXT_FACTORY = "org.jboss.naming.JNDIView";
    public static final String WEBSPHERE_INITIAL_CONTEXT_FACTORY = "com.ibm.websphere.naming.WsnInitialContextFactory";

    public SqlAccess() {
        try {
            initial();
            conn.setAutoCommit(true);
        }
        catch (Exception exp) {
        }
    }
    public SqlAccess(String jndi,String serverType) {
        this.serverType = serverType;
        this.jndiName = jndi;
        try {
            initial();
            conn.setAutoCommit(true);
        }
        catch (Exception exp) {
        }
    }

    public static SqlAccess createConn(String ds) throws Exception {
        SqlAccess sq = new SqlAccess(ds,"websphere");
        if (sq == null || sq.conn == null)
            throw new Exception("Errorx");
        return sq;
    }

    public static SqlAccess createConn() throws Exception {
        return createConn("");
    }

    public static void main(String[] args) {

    }

    public static final String ST_WEBSPHERE = "websphere";
    public static final String ST_WEBLOGIC = "weblogic";
    public static final String ST_TOMCAT = "tomcat";
    public static final String ST_JBOSS = "jboss";
    public static final String ST_RESIN = "resin";

    public void initial() throws SQLException {
        try {
            Context ctx = null;
            DataSource ds = null;
            String dsName = this.jndiName;
            try {
                count = ++begincont;
            }
            catch (Exception e) {
                begincont = 0;
                count = ++begincont;
            }

            System.out.println("[count]"+count);

            if (ST_WEBLOGIC.equals(serverType)) {
                Properties props = new Properties();
                //取数据库连接
                props.put("weblogic.codeset", "GBK");
                Hashtable parms = new Hashtable();
                parms.put(    Context.INITIAL_CONTEXT_FACTORY,    this.WLS_INITIAL_CONTEXT_FACTORY);
                ctx = new InitialContext(parms);
            }
            else if (ST_JBOSS.equals(serverType)) {
                System.out.println("Jboss connection init");
                ctx = new InitialContext();
                dsName = "java:/" + dsName;
            }
            else if (ST_RESIN.equals(serverType)) {
                System.out.println("Resin Connection init");
                ctx = new InitialContext();
                dsName = "java:comp/env/" + dsName;
            }
            else if (ST_WEBSPHERE.equals(serverType)) {
                System.out.println("Websphere Connection init");
                Hashtable prop = new Hashtable();
                prop.put(Context.INITIAL_CONTEXT_FACTORY,this.WEBSPHERE_INITIAL_CONTEXT_FACTORY);
                ctx = new InitialContext(prop);
            }
            else if (ST_TOMCAT.equals(serverType)) {
                System.out.println("Tomcat JNDI Connection init");
                ctx = new InitialContext();
                dsName = "java:comp/env/" + dsName;
            }

            System.out.println("[SqlAccess]dsName:" + dsName + "...");

            ds = (DataSource) ctx.lookup(dsName);
            conn = ds.getConnection();

            //--System.out
            System.out.println("conn:" + conn.toString());
            logmap.put(conn,count+"");
            //--System.out
            System.out.println("ConnectionPool:making a connection...[" + count + "]");
            //--System.out
            //--System.out
            //stmt = conn.createStatement();
            isConnDB = true;

        }
        catch (SQLException sqle) {
            sqle.printStackTrace();
            System.out.println("SQLException during connection(): " + sqle.getMessage());
            throw sqle;
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }

    //设置AutoCommit
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        try {
            if (isConnDB)
                conn.setAutoCommit(autoCommit);
        }
        catch (SQLException sqle) {
            System.out.println("SQLException during autoCommit(): " + sqle.getMessage());
            throw sqle;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());

        }
    }

    //执行Commit命令
    public void commit() throws SQLException {
        try {
            if (isConnDB)
                conn.commit();
        }
        catch (SQLException sqle) {
            System.out.println("SQLException during commit(): " + sqle.getMessage());
            throw sqle;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    //执行Rollback命令
    public void rollback() {
        try {
            if (isConnDB)
                conn.rollback();
        }
        catch (SQLException sqle) {
            System.out.println("SQLException during rollback(): " + sqle.getMessage());
            //throw sqle;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());

        }
    }

    //查询与数据库之间的连接是否关闭,true - 有连接:false - 没连接
    public boolean isConnectDB() {
        return isConnDB;
    }

    //关闭连接
    public void close() {

        try {

            if (conn != null)
                conn.close();
            logmap.remove(conn);
            logmap.remove("" + count);
            System.out.println("ConnectionPool::Closing connection...[" + count + "]\n");
        }
        catch (SQLException sqle) {
            System.out.println("SQLException during close(): " + sqle.getMessage());
            //throw sqle;
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    //public static String SERVER="JBOSS";
    //public static String SERVER="WEBLOGIC";
    /**
     * Returns the logmap.
     * @return HashMap
     */
    public static HashMap getLogmap() {
        return logmap;
    }

    /**
     * Returns the count.
     * @return int
     */
    public int getCount() {
        return count;
    }

}

使用此方法获取连接,需要从容器中配置连接池

调用方法演示:

    SqlAccess sa = new SqlAccess("HIS", "websphere");
    if (sa != null) {
        System.out.println("成功连接=" + sa.conn);
    } else {
        System.out.println("失败连接=" + sa.conn);
    }
    Connection hisConn = sa.conn;

java直接访问JNDI工具代码的更多相关文章

  1. java获取时间整点工具代码

    /**获取上n个小时整点小时时间 * @param date * @return */ public static String getLastHourTime(Date date,int n){ C ...

  2. 使用poco 的NetSSL_OpenSSL 搭建https 服务端,使用C++客户端,java 客户端访问,python访问(python还没找到带证书访问的代码.)

    V20161028 由于项目原因,需要用到https去做一些事情. 这儿做了一些相应的研究. 这个https 用起来也是折腾人,还是研究了一周多+之前的一些积累. 目录 1,java client 通 ...

  3. java服务器访问其他服务器工具类编写

    java服务器访问其他服务器工具类编写适合各种消息推送及微服务交互 package com.xiruo.medbid.components; import com.xiruo.medbid.util. ...

  4. 【JAVA系列】使用JavaScript实现网站访问次数统计代码

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[JAVA系列]使用JavaScript实现网站 ...

  5. Java中常用的设计模式代码与理解

    Java中常用的设计模式代码与理解 一.单例模式 1.饿汉式 (太饿了,类加载的时候就创建实例) /** * 饿汉式单例模式 */ public class HungrySingleInstance ...

  6. Java并发包同步工具之Exchanger

    前言 承接上文Java并发包同步工具之Phaser,讲述了同步工具Phaser之后,搬家博客到博客园了,接着未完成的Java并发包源码探索,接下来是Java并发包提供的最后一个同步工具Exchange ...

  7. Java安全之JNDI注入

    Java安全之JNDI注入 文章首发:Java安全之JNDI注入 0x00 前言 续上篇文内容,接着来学习JNDI注入相关知识.JNDI注入是Fastjson反序列化漏洞中的攻击手法之一. 0x01 ...

  8. Java线程的并发工具类

    Java线程的并发工具类. 一.fork/join 1. Fork-Join原理 在必要的情况下,将一个大任务,拆分(fork)成若干个小任务,然后再将一个个小任务的结果进行汇总(join). 适用场 ...

  9. java性能优化常用工具jmap、jstack

    jmap:java内存映像工具 jmap用于生成堆转储快照,比较常用的option包括-heap,-histo,-dump [root@localhost script]# jmap -h Usage ...

随机推荐

  1. ACM数据结构-并查集

    ACM数据结构-并查集   并查集,在一些有N个元素的集合应用问题中,我们通常是在开始时让每个元素构成一个单元素的集合,然后按一定顺序将属于同一组的元素所在的集合合并,其间要反复查找一个元素在哪个集合 ...

  2. 青岛Uber优步司机奖励政策(8/10-8/16)

    亲爱的Uber青岛优步的大司机朋友们,又到了每周发布奖励细则的时刻啦!下一周的奖励与上周有所不同,请一定要仔细按照自己的情况阅读!另外,之前参与过投票并表示想加入新小时保底政策的老司机朋友们从本周起, ...

  3. day 3 创建窗口,移动-函数版

    1.创建窗口 #-*- coding:utf-8 -*- import pygame import time def main(): #1.创建窗口 screen = pygame.display.s ...

  4. Entity Framework Core 导航属性 加载数据

    Loading Related Data https://docs.microsoft.com/en-us/ef/core/querying/related-data Eager loading me ...

  5. Entity Framework Core 选择数据表的外键

    entityTypeBuilder .HasOne<GeraeteArt>() .WithMany(p => p.Geraete) .HasForeignKey(b => b. ...

  6. 编译Chromium出现warning C4819的解决办法

    编译Chromium时出现 warning C4819: The file contains a character that cannot be represented in the current ...

  7. Linux管道及I/O重定向

    I/O: 系统设定 默认输入设备:标准输入,STDIN,0 默认输出设备:标准输出,STDOUT,1 标准错误输出:STDERR,2 属于不同的数据流 标准输入:键盘 标准输出和错误输出:显示器 I/ ...

  8. Unity Lighting - Choosing a Lighting Technique 选择照明技术(一)

      Choosing a Lighting Technique 选择照明技术 https://unity3d.com/cn/learn/tutorials/topics/graphics/choosi ...

  9. Java开发工程师(Web方向) - 02.Servlet技术 - 期末考试

    Servlet课程考试 Servlet课程考试 Servlet课程考试 总分:55分 限定时间:120分钟 进入考试 答案已成功提交!请耐心等待成绩公布 Servlet课程考试: 1(12分) 简单谈 ...

  10. 【system.string】使用说明

    对象:system.string 说明:提供一系列针对字符串类型的操作 目录: 方法 返回 说明 system.string.isBlank( string ) [True | False]  检测参 ...