JNDI数据源配置连接Oracle数据库

来源:互联网 发布:ubuntu如何升级内核 编辑:程序博客网 时间:2024/05/20 21:48

META-INF/context.xml

<?xml version="1.0" encoding="UTF-8" ?><Context>    <Resource name="jdbc/oracle"              auth="Container"              type="javax.sql.DataSource"              driverClassName="oracle.jdbc.driver.OracleDriver"              url="jdbc:oracle:thin:@192.168.191.1:1521:XE"              username="hr"              password="qweqwe"              maxActive="20"              maxIdle="10"              maxWait="-1"    /></Context>

JNDIUtils.java

public class JNDIUtils {    public static DataSource ds;    static {        try {            Context context = new InitialContext();           ds = (DataSource) context.lookup("java:comp/env/jdbc/oracle");        } catch (NamingException e) {            e.printStackTrace();        }    }    public static Connection getConnection() {        Connection conn = null;        try {            conn = ds.getConnection();        } catch (SQLException e) {            e.printStackTrace();        }        return conn;    }    public static void closeConnection(PreparedStatement ps, ResultSet rs, Connection conn) throws SQLException {        if (ps != null) {            ps.close();        }        if (rs != null) {            rs.close();        }        if (conn != null) {            conn.close();        }    }}

接下来在代码中连接测试:

    public int getCount() {        Connection conn = JNDIUtils.getConnection();        PreparedStatement ps = null;        ResultSet rs = null;        int count = 0;        String sql = "SELECT count(*) as COUNT from EMPLOYEES";        try {            ps = conn.prepareStatement(sql);            rs = ps.executeQuery();            while (rs.next()) {                count = rs.getInt("COUNT");            }        } catch (SQLException e) {            e.printStackTrace();        } finally {            try {                JNDIUtils.closeConnection(ps, rs, conn);            } catch (SQLException e) {                e.printStackTrace();            }        }        return count;    }