JNDI连接数据库模型

类别:Java 点击:0 评论:0 推荐:

package DBUtil;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

public class DBConnection {
    private Connection conn = null;
    private Statement stmt = null;
    private ResultSet rs = null;
    private int resultNum = 0;

    /**
     * 构造函数
     * 找到数据源,并用这个数据源创建连接
     */
    public DBConnection() {
        try {
            Context ctx = new InitialContext();
     if (ctx == null) throw new Exception("No Context");
     DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
            if (ds == null) throw new Exception("jdbc/oracle is an unknown DataSource");
            conn = ds.getConnection();
            stmt = conn.createStatement();
        } catch (Exception e) {
            System.out.println("naming:" + e.getMessage());
        }
    }

    /**
     * 执行SQL语句:查询记录
     * @param sql SQL语句
     * @return ResultSet 记录集
     */
    public ResultSet executeQuery(String sql) {
        rs = null;
        try {
            rs = stmt.executeQuery(sql);
        } catch(SQLException se) {
            System.out.println("Query error:" + se.getMessage());
        }
        return rs;
    }

    /**
     * 执行SQL语句 :插入与更新记录
     * @param sql SQL语句
     * @return int resultNum 更新的记录数
     */
    public int executeUpdate(String sql) {
        resultNum=0;
        try {
            resultNum = stmt.executeUpdate(sql);
        } catch (SQLException se) {
            System.err.println("Update error:" + se.getMessage());
        }
        return resultNum;
    }

    /**
     * 关闭连接
     */
    public void close() {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stmt != null) {
               stmt.close();
               stmt = null;
            }
            if (conn != null) {
                conn.close();
                conn = null;
            }
        } catch (SQLException se) {
            System.out.println("close error:" + se.getMessage());
        }
    }
}

本文地址:http://com.8s8s.com/it/it11313.htm