JDBC接続データベースクラス(主にストレージ・プロシージャ用)

27381 ワード

データベース接続クラス(SQLCONN)はMSSQL 2005でテストに合格しましたが、後で英語をよく勉強して鬼ごっこAPIに適応することにしたので、注釈はすべて全英です.レベルが限られているので、間違いがあれば指摘してください~~
また、ここで返されるレコードはArrayListに封入されているので、リアルタイムで更新する操作は无力diesi~実は参学C#のようにパラメータのクラスに封入することもできますが、私はとても怠け者でやめました~~~
最近资料を见ている时、JAVAの効率を批判する人や文章をたくさん见ました.JAVAのゴミを言う人もいます.いいでしょう.JAVAのプログラミング思想さえ通読していない人が言っているキックアスの言叶は私は相手にしません.私自身もJAVAについてよく理解していないので、評価もしません.しかし、このような黒は脳の残粉と同じように、黒には水平の粉が必要だと思っています.もしある物体を全く知らない場合、勝手に黒を消して、勝手に粉を消して、これは脳の残と何の違いがありますか?
まとめてみると、JavaよりC#のデータベース接続のほうが本気ではないとか、JDBCがあまりできていないとか、JDBCがプログラマーに直面していることは多くないとか(古くからの接続データベースモデルを考えると、今のJDBCはあまり作られていないとは言えません)C#のDataSetなどいろいろなDB容器を見て涙が出ました~でもこれこそJAVAの素晴らしいところではないでしょうか?ないものを一つ作ればいい!
最后にC#とJavaは私の感じにC#は私に2つの鬼に4つの2を持ってきてそれから私にこのように出て胜ったことを教えてくれて、JAVAは私に1つの大きい鬼に1つの黒桃に2つの赤い桃に2つの四角い片に2つの小さい鬼に1つの梅の花2を持ってきてそれから私にあなたが自分で见て騒ぎます~~
=======午後に書くと======
怒りでコードを変更するのは本当に難しいです~~
=======2013-7-5に書いてあると=======
実はこのクラスはもう私に直された差は多くありません...しかし、全体的な考え方は変わっていません..以前はResultSetとDataSetの違いが分からなかった.今は分かったようですが、ダイナミックデータです.静的データです.今の感覚では、これらの静的容器は実は役に立たないと思います.のJPAのルールに従ってO/Rモデルで游べば必要ないみたいなので..
/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package dataanalysis_erp_plug.DataAnalysis;



import java.sql.*;

import java.util.*;

import java.util.logging.*;



/**

 *

 * @author Administrator

 *

 * private function: open(): open a connection; close(): close a connection;

 *

 * public function: runSQL(): run a sql code and return a number. This number should be a number of be affected rows; getResultListFromProc(): run a stored procedure and return a ResultSet

 * getResultSetFromSQL(): run sql code and return a ResultSet

 *

 */

public class SQLCONN {

    

    public ArrayList<Object[]> table = new ArrayList<Object[]>();

    public ArrayList outputParams = new ArrayList();

    

    private Connection conn = null;

    private String driver, serverName, userName, password;

    private ArrayList<Object[]> _outputParams = new ArrayList<Object[]>();

    private ArrayList<Object[]> _inputParams = new ArrayList<Object[]>();



    public SQLCONN(String driver, String serverName, String userName, String password) {

        this.serverName = serverName; //include a dbName here, ex: "jdbc:sqlserver://192.168.0.251\\GSSL; DatabaseName=Materials"

        this.driver = driver;

        this.password = password;

        this.userName = userName;

    }



    public int runSQL(String sql) {

        int returnNumber = -1;

        try {

            this.open();

            try (Statement stmt = conn.createStatement()) {

                returnNumber = stmt.executeUpdate(sql);

            }

        } catch (ClassNotFoundException | SQLException ex) {

            Logger.getLogger(SQLCONN.class.getName()).log(Level.SEVERE, null, ex);

        } finally {

            this.close();

            return returnNumber;

        }

    }



    public ResultSet getResultSetFromSQL(String sql) {

        ResultSet returnResultSet = null;

        try {

            this.open();

            try (Statement stmt = conn.createStatement()) {

                returnResultSet = stmt.executeQuery(sql);

                returnResultSet.close();

            }

        } catch (ClassNotFoundException | SQLException ex) {

            Logger.getLogger(SQLCONN.class.getName()).log(Level.SEVERE, null, ex);

        } finally {

            this.close();

            return returnResultSet;

        }

    }



    /*

     * input Params:

     * procName: database stored process's name (String)

     * inputs: an ArrayList with an Object Array in it. Objcet[0] means input params name (String), object[1] means input params value (Object)

     * outputs: an ArrayList with an Object Array in it. Objcet[0] means output params name (String), object[1] means output params type (int from java.sql.Types.*)

     * 

     * output Params:

     * is a ArrayList. [0] is a ArrayList<Object[]> descript ResultSet. [1 ... n] is a set of database stored process output Params.

     * 

     * throw an exception when the number of inputparam don't match

     * 

     */

    

    public void runProc(String procName) throws Exception {

         int i = 0;

         this.outputParams.clear();

         this.table.clear();

         String callString = "{call " + procName + "(";

         if (this._inputParams.isEmpty() && this._outputParams.isEmpty()) {

             callString = callString + ")}";

         } else {

             callString = callString + "?";

             if (!this._inputParams.isEmpty()) {

                 for (i = 1; i < this._inputParams.size(); i++) {

                     callString = callString + ",?";

                 }

             }

             if (!this._outputParams.isEmpty()) {

                 for (i = (this._inputParams.isEmpty() ? 1 : 0); i < this._outputParams.size(); i++) {

                     callString = callString + ",?";

                 }

             }

             callString = callString + ")}";

         }

         try {

             this.open();

             try (CallableStatement cstmt = conn.prepareCall(callString)) {

                 //init input params

                 if (this._inputParams != null) {

                     for (i = 0; i < this._inputParams.size(); i++) {

                         switch(this._inputParams.get(i).length){

                             case 2:

                                 cstmt.setObject((String) this._inputParams.get(i)[0], this._inputParams.get(i)[1]);

                                 break;

                             case 3:

                                 cstmt.setObject((String) this._inputParams.get(i)[0], this._inputParams.get(i)[1], (Integer) this._inputParams.get(i)[2]);

                                 break;

                             case 4:

                                 cstmt.setObject((String) this._inputParams.get(i)[0], this._inputParams.get(i)[1], (Integer) this._inputParams.get(i)[2], (Integer) this._inputParams.get(i)[3]);

                                 break;

                             default:

                                 throw new Exception("Error: the number of input param's input param is not match");

                         }

                     }

                 }

                 //init output params

                 if (this._outputParams != null) {

                     for (i = 0; i < this._outputParams.size(); i++) {

                         switch(this._outputParams.get(i).length){

                             case 2:

                                 cstmt.registerOutParameter((String) this._outputParams.get(i)[0], (Integer) this._outputParams.get(i)[1]);

                                 break;

                             case 3:

                                 cstmt.registerOutParameter((String) this._outputParams.get(i)[0], (Integer) this._outputParams.get(i)[1], (Integer) this._outputParams.get(i)[2]);

                                 break;

                             default:

                                 throw new Exception("Error: the number of output param's input param is not match");

                         }

                     }

                 }

                 cstmt.execute();

                 //bind the ResultSet to HashMap

                 ResultSet rs = cstmt.getResultSet();

                 ResultSetMetaData rsmd = rs.getMetaData();

                 if (rs != null) {

                     while (rs.next()) {

                         Object[] col = new Object[rsmd.getColumnCount()];

                         for (i = 0; i < rsmd.getColumnCount(); i++) {

                             col[i] = rs.getObject(i + 1);

                         }

                         this.table.add(col);

                     }

                 } else {

                     this.table = null;

                 }

                 //get output params

                 for (i = 0; i < this._outputParams.size(); i++) {

                     this.outputParams.add(cstmt.getObject((String) this._outputParams.get(i)[0]));

                 }

             }

         } catch (ClassNotFoundException | SQLException ex) {

             Logger.getLogger(SQLCONN.class.getName()).log(Level.SEVERE, null, ex);

         } finally {

             this._inputParams.clear();

             this._outputParams.clear();

             this.close();

         }

    }

    

    /*

     * set input params

     */

    public void addInputParam(String paramName, Object value, int SQLType, int scale) {

        Object[] output = new Object[4];

        output[0] = paramName;

        output[1] = value;

        output[2] = SQLType;

        output[3] = scale;

        this._inputParams.add(output);

    }

    

    public void addInputParam(String paramName, Object value, int SQLType) {

        Object[] output = new Object[3];

        output[0] = paramName;

        output[1] = value;

        output[2] = SQLType;

        this._inputParams.add(output);

    }

    

    public void addInputParam(String paramName, Object value) {

        Object[] output = new Object[2];

        output[0] = paramName;

        output[1] = value;

        this._inputParams.add(output);

    }

    

    /*

     * set output params

     */

    public void addOutputParams(String paramName, int SQLType, int scale) {

        Object[] output = new Object[3];

        output[0] = paramName;

        output[1] = SQLType;

        output[2] = scale;

        this._outputParams.add(output);

    }

    

    public void addOutputParams(String paramName, int SQLType) {

        Object[] output = new Object[2];

        output[0] = paramName;

        output[1] = SQLType;

        this._outputParams.add(output);

    }



    private void open() throws ClassNotFoundException, SQLException {

        Class.forName(this.driver);

        this.conn = DriverManager.getConnection(this.serverName, this.userName, this.password);

        System.out.println("connected");

    }



    private void close() {

        try {

            this.conn.close();

            System.out.println("close");

        } catch (SQLException ex) {

            Logger.getLogger(SQLCONN.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

}

 
呼び出し:
 
/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

package dataanalysis_erp_plug;



import dataanalysis_erp_plug.DataAnalysis.*;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.*;

import java.util.logging.Level;

import java.util.logging.Logger;



/**

 *

 * @author Administrator

 */

public class DataAnalysis_ERP_Plug {



    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

        String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

        String userName = "SQL   ";

        String password = "  ";

        String serverName = "jdbc:sqlserver://SQL    \\   ;";

        String dbName = "DatabaseName=    "; //allow empty, default value = "";

        SQLCONN sqlconn = new SQLCONN(driver, serverName + dbName, userName, password);

        

        //define input params

        sqlconn.addInputParam("input", "caca", java.sql.Types.VARCHAR, 50);

        //define output params

        sqlconn.addOutputParams("return", java.sql.Types.VARCHAR);

        try {

            sqlconn.runProc("testProc_noIOParam");

        } catch (Exception ex) {

            Logger.getLogger(DataAnalysis_ERP_Plug.class.getName()).log(Level.SEVERE, null, ex);

        }

        if (sqlconn.table.isEmpty()) {

            System.out.println("null");

        } else {

            System.out.println(sqlconn.table.get(0)[0]);

            System.out.println(sqlconn.outputParams.get(0));

            System.out.println("not null");

        }

    }

}