天天看點

java資料庫操作類

代碼如下:

package xaut.dataPool;

import java.util.ArrayList;

import java.sql.CallableStatement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.sql.DataSource;

import javax.naming.InitialContext;

import javax.naming.Context;

public class DatabaseBean {

    private DatabaseConfigure databaseConfigure = null;

    public Connection conn = null;

    public Statement stmt = null;

    private CallableStatement cstmt = null;

    public DatabaseBean(DatabaseConfigure databaseConfigure) {

        this.databaseConfigure = databaseConfigure;

    }

    /**

     * 擷取目前連接配接

     *

     * @return 傳回目前連接配接connection

     */

    public Connection getConnection(){

        return this.conn;

     * 直接連接配接資料庫,效率低

     * @throws Exception 連接配接失敗異常

    public void getDirectConnect()throws Exception{

        if(this.conn==null){

            try {

                Class.forName(databaseConfigure.getJdbcDriver());

            } catch (ClassNotFoundException e) {

                System.out.println(" class not found: " + e.getMessage());

                e.printStackTrace();

                throw new SQLException("-Database driver notFind ");

            }

                conn = DriverManager.getConnection(databaseConfigure

                        .getDatabaseURL(), databaseConfigure

                        .getDatabaseName(), databaseConfigure

                        .getDatebasePassword());

            } catch (SQLException sqlex) {

                System.err.println("DatabaseBean connection error"

                        + sqlex.getMessage());

                sqlex.printStackTrace();

                throw new SQLException("-Database connection error ");

        }

     * 通過資料庫連接配接池連接配接,效率高

     * 需要配置資料庫連接配接池

    public void getConnectFromdataPool()throws Exception{

        if (this.conn == null) {

            Context initCtx = new InitialContext();

            DataSource ds = (DataSource) initCtx.lookup(this.databaseConfigure.getDatapool());

            if (ds != null)

                conn = ds.getConnection();

     * 此函數以後不建議使用,由于曆史遺留問題保留

     * @throws Exception

    public void connection() throws Exception {

/*

            // 先通過資料庫連接配接池連接配接

            if (this.databaseConfigure.getDatapool() != null) {

                Context initCtx = new InitialContext();

                DataSource ds = (DataSource) initCtx.lookup(this.databaseConfigure.getDatapool());

                if (ds != null)

                    conn = ds.getConnection();

            } else {

*/       

                //如果沒有資料庫連接配接池,則直接連接配接

                try {

                    Class.forName(databaseConfigure.getJdbcDriver());

                } catch (ClassNotFoundException e) {

                    System.out.println(" class not found: " + e.getMessage());

                    e.printStackTrace();

                    throw new SQLException("-Database driver notFind ");

                }

                    conn = DriverManager.getConnection(databaseConfigure

                            .getDatabaseURL(), databaseConfigure

                            .getDatabaseName(), databaseConfigure

                            .getDatebasePassword());

                } catch (SQLException sqlex) {

                    System.err.println("DatabaseBean connection error"

                            + sqlex.getMessage());

                    sqlex.printStackTrace();

                    throw new SQLException("-Database connection error ");

            //}

    public void disconnect() throws SQLException {

        try {

            if (stmt != null) {

                stmt.close();

                //注意調用close後,該變量不為null,如果再以stmt!=null為條件,将引發錯誤

                stmt=null;

            if (conn != null) {

                conn.close();

                //注意調用close後,與資料庫的連接配接返還給了資料庫連接配接池,但該變量不為null,

                //如果再以判斷conn!=null為條件,将引發錯誤

                conn=null;

        } catch (SQLException e) {

            System.err.println("DatabaseBean disconnect error");

            e.printStackTrace();

            throw new SQLException("-Database disConnection error ");

    public boolean isConnected() {

        return (conn != null);

    public ResultSet excutequery(String sql) throws SQLException {

        ResultSet rs1 = null;

            if (!isConnected())

                this.connection();

            if (this.stmt == null)

                stmt = conn.createStatement();

            rs1 = stmt.executeQuery(sql);

            return rs1;

        } catch (Exception e) {

            System.err.println("DatabaseBean query error" + e.getMessage());

            throw new SQLException("-Query error ");

    public boolean execute(String sql) throws SQLException {

            return stmt.execute(sql);

            System.err.println("DatabaseBean execute error" + e.getMessage());

            throw new SQLException("-Execute error ");

    public void statementClose() {

            if (stmt != null)

    public ResultSet callQueryProcedure(String sql) throws SQLException {

        ResultSet rs = null;

            if (this.cstmt == null)

                cstmt = conn.prepareCall(sql);

            cstmt.executeQuery();

            System.err.println("DatabaseBean callQueryProcedure error"

                    + e.getMessage());

            throw new SQLException("-CallQueryProcedure error ");

        return rs;

    public boolean callExecuteProcedure(String sql) throws SQLException {

            return cstmt.execute();

            System.err.println("DatabaseBean callExecuteProcedure error"

            throw new SQLException("-CallExecuteProcedure error ");

    public void executeBatch(ArrayList<String> sqlBatch) throws SQLException {

            conn.setAutoCommit(false);

            for (int i = 0; i < sqlBatch.size(); i++) {

                stmt.addBatch((String) sqlBatch.get(i));

            stmt.executeBatch();

            conn.commit();

            conn.setAutoCommit(true);

            System.err.println("DatabaseBean executeBatch error"

            throw new SQLException("-ExecuteBatch error ");

    public PreparedStatement createprepareStatement(String paramSQL)

            throws SQLException {

            return conn.prepareStatement(paramSQL);

            System.err.println("DatabaseBean PreparedStatement error");

            throw new SQLException("-DatabaseBean PreparedStatement error ");

    public void transactionStart() throws SQLException {

            System.err.println("DatabaseBean transactionStart");

            throw new SQLException("-Transaction start error ");

    public void transactionEnd() throws SQLException {

            System.err.println("DatabaseBean transactionEnd error");

            throw new SQLException("-Transaction end error:");

    public void transactionRollback() throws SQLException {

            conn.rollback();

            System.err.println("DatabaseBean transactionRollback error");

            throw new SQLException("-Transaction rollback error ");

}