jdbcwork.java

  1. /**
  2.  * Title:        數據庫連接及操作類
  3.  * Description:  加載各種數據庫驅動程序、連接數據庫、提交SQL及返回結果集。
  4.  * @date :       2006-4-3
  5.  * @author :     zhanglei
  6.  * @version :    1.0
  7.  */
  8. package server;
  9. import java.sql.*;
  10. import java.util.*;
  11. import java.io.*;
  12. //import oracle.sql.*;
  13. public class JdbcWork {
  14.     public static Connection conn = null;
  15.     private Statement stmt = null;
  16.     private DomXML DomXML = MainServer.DomXML;
  17.     public Connection ConnectDB() {
  18.         String database = "";
  19.         String driverName = "";
  20.         String databaseURL = "";
  21.         String user = "";
  22.         String password = "";
  23.         try {
  24.             DomXML.GetBeginItem("JdbcConfig");
  25.             database = DomXML.GetItemVal("database");
  26.             DomXML.GetBeginItem(database);
  27.             driverName = DomXML.GetItemVal("driverName");
  28.             databaseURL = DomXML.GetItemVal("databaseURL");
  29.             user = DomXML.GetItemVal("username");
  30.             password = DomXML.GetItemVal("password");
  31.         }
  32.         catch (Throwable t) {
  33.             SaveLog.SetInfo("數據庫配置文件讀取錯誤!"1);
  34.            
  35.             return null;
  36.         }
  37.         try {
  38.             Class.forName(driverName);//安裝驅動程序
  39.             //System.out.println ("drive ok");
  40.         }
  41.         catch (java.lang.ClassNotFoundException e) {
  42.             SaveLog.SetInfo("加載JDBC驅動失敗!"1);
  43.             SaveLog.SetInfo(e.getMessage(), 2);
  44.             return null;
  45.         }
  46.         try {
  47.             conn = java.sql.DriverManager.getConnection(databaseURL, user, password);
  48.             conn.setAutoCommit(false);
  49.             //System.out.println ("conn ok");
  50.             return conn;
  51.         }
  52.         catch (java.sql.SQLException e) {
  53.             SaveLog.SetInfo("數據庫連接失敗!"2);
  54.             SaveLog.SetInfo("SQLException: " + e.getMessage(), 2);
  55.             return null;
  56.         }
  57.     }
  58.     public int ExecSql(String sql) {
  59.         Statement sqlStatement = null;
  60.         if (conn == null) {
  61. //      SaveLog.SetInfo("ExecSql conn NULL", 2);
  62.             conn = ConnectDB();
  63.         }
  64.         try {
  65.             sqlStatement = conn.createStatement();
  66.             try {
  67.                 sqlStatement.executeUpdate(sql);
  68.                 sqlStatement.close();
  69.                 conn.commit();
  70.                 //System.out.println (sql+"執行成功!");
  71.                 return 1;
  72.             }
  73.             catch (SQLException ex) {
  74.                 SaveLog.SetInfo(sql + " ExecSql1:" + ex, 2);
  75.                 conn.rollback();
  76.             }
  77.         }
  78.         catch (SQLException ex) {
  79.             SaveLog.SetInfo(sql + " ExecSql2:" + ex, 2);
  80.         }
  81.         return -1;
  82.     }
  83.     public int PstmtExecSql(String sql) {
  84.         PreparedStatement pstmt = null;
  85.         if (conn == null) {
  86. //      SaveLog.SetInfo("PstmtExecSql conn NULL", 2);
  87.             conn = ConnectDB();
  88.         }
  89.         try {
  90.             try {
  91.                 pstmt = conn.prepareStatement(sql);
  92.                 pstmt.executeUpdate();
  93.                 pstmt.close();
  94.                 //System.out.println (sql+"執行成功!");
  95.                 return 0;
  96.             }
  97.             catch (SQLException e) {
  98.                 conn.rollback();
  99.                 SaveLog.SetInfo(sql + " PstmtExecSql1:" + e, 2);
  100.                 return -1;
  101.             }
  102.         }
  103.         catch (SQLException ex) {
  104.             SaveLog.SetInfo(sql + " PstmtExecSql:2" + ex, 2);
  105.         }
  106.         return -1;
  107.     }
  108.     /**
  109.      *PreparedStatement 執行SQL語句,並提交
  110.      *@param sql   SQL語句
  111.      */
  112.     public int PstmtExecSql(Vector sql, Vector zp) {
  113.         int blobflag = 0;
  114.         /*    if (zp.size() == sql.size()) {
  115.               flag = 1;
  116.             }
  117.          }
  118.          */
  119.         sun.misc.BASE64Decoder base64Decoder = new sun.misc.BASE64Decoder();
  120.         byte b[] = null;
  121.         InputStream is = null//= new ByteArrayInputStream()
  122.         PreparedStatement pstmt = null;
  123.         String Sql = null;
  124. //        SaveLog.SetInfo("insert into table start", 2);
  125.         if (conn == null) {
  126.             SaveLog.SetInfo("PstmtExecSql Vconn NULL"2);
  127.             conn = ConnectDB();
  128.         }
  129.         try {
  130.             try {
  131.                 for (int j = 0; j < sql.size(); j++) {
  132.                     Sql = sql.get(j).toString();
  133.                     if (Sql.indexOf(" ? ") > 1) {
  134.                         blobflag = 1;
  135.                     }
  136.                     else {
  137.                         blobflag = 0;
  138.                     }
  139.                     pstmt = conn.prepareStatement(sql.get(j).toString());
  140.                     if (blobflag == 1) {
  141.                         try {
  142.                             b = base64Decoder.decodeBuffer(zp.get(j).toString());
  143.                             is = new ByteArrayInputStream(b);
  144.                             pstmt.setBinaryStream(1, is, is.available());
  145.                         }
  146.                         catch (IOException e) {
  147.                             System.out.println("BLOB Error:" + e);
  148.                         }
  149.                     }
  150.                     pstmt.executeUpdate();
  151.                     pstmt.close();
  152.                 }
  153.                 return 0;
  154.             }
  155.             catch (SQLException e) {
  156.                 conn.rollback();
  157.                 SaveLog.SetInfo(Sql + " VPstmtExecSql1:" + e, 2);
  158.                 return -1;
  159.             }
  160.         }
  161.         catch (SQLException ex) {
  162.             SaveLog.SetInfo(Sql + " VPstmtExecSql2:" + ex, 2);
  163.             return -1;
  164.         }
  165.     }
  166.     /**
  167.      *提交PreparedStatement 的SQL語句
  168.      */
  169.     public int PstmtCommit() {
  170.         if (conn == null) {
  171.             conn = ConnectDB();
  172.         }
  173.         try {
  174.             try {
  175.                 conn.commit();
  176.                 return 0;
  177.             }
  178.             catch (SQLException e) {
  179.                 SaveLog.SetInfo("PstmtCommit1:" + e, 2);
  180.                 conn.rollback();
  181.                 return -1;
  182.             }
  183.         }
  184.         catch (SQLException ex) {
  185.             SaveLog.SetInfo("PstmtCommit2:" + ex, 2);
  186.             return -1;
  187.         }
  188.     }
  189.     /**
  190.      *得到結果集
  191.      *@param sql 輸入SQL語句
  192.      *@param out 輸出ResultSet結果集
  193.      */
  194.     public ResultSet SelectSql(String sql) {
  195.         if (conn == null) {
  196. //      SaveLog.SetInfo("SelectSql conn NULL", 2);
  197.             conn = ConnectDB();
  198.         }
  199.         Statement stmt = null;
  200.         try {
  201.             stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, //TYPE_SCROLL_INSENSITIVE
  202.                                         ResultSet.CONCUR_READ_ONLY);
  203.             return stmt.executeQuery(sql);
  204.         }
  205.         catch (Exception e) {
  206.             SaveLog.SetInfo(sql + " SelectSql:" + e, 2);
  207.             CloseConn();
  208.             return null;
  209.         }
  210.     }
  211.     /**
  212.      *得到結果集
  213.      *@param out 輸出Statment
  214.      */
  215.     public Statement GetStatment() {
  216.         if (conn == null) {
  217. //      SaveLog.SetInfo("GetStatment conn NULL", 2);
  218.             conn = ConnectDB();
  219.         }
  220.         try {
  221.             stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, //TYPE_SCROLL_INSENSITIVE
  222.                                         ResultSet.CONCUR_READ_ONLY);
  223.             return stmt;
  224.         }
  225.         catch (Exception e) {
  226.             SaveLog.SetInfo(" GetStatment 異常:" + e, 2);
  227.             CloseConn();
  228.             return null;
  229.         }
  230.     }
  231.     /**
  232.      *關閉Statment
  233.      */
  234.     public void CloseStatment() {
  235.         try {
  236.             if (stmt != null) {
  237.                 stmt.close();
  238. //System.out.println("Statmentclose()");
  239.             }
  240.         }
  241.         catch (Exception e) {
  242.             SaveLog.SetInfo("CloseStatment 異常:" + e, 2);
  243.         }
  244.     }
  245.     /**
  246.      *得到記錄數 注意:在得到結果集後使用,執行後使記錄集定位到first()
  247.      *@param sql 輸入ResultSet
  248.      *@param out 輸出ResultSet結果集記錄數
  249.      */
  250.     public int GetCount(ResultSet Rs) {
  251.         int recSum = 0;
  252.         try {
  253.             Rs.next();
  254.             /*      do {
  255.                     recSum++;
  256.                   }
  257.                   while (Rs.next());*/
  258.             Rs.last();
  259.             recSum = Rs.getRow();
  260.             Rs.first();
  261.             return recSum;
  262.         }
  263.         catch (Exception e) {
  264.             SaveLog.SetInfo("GetCount(ResultSet) 異常:" + e, 2);
  265.             return 0;
  266.         }
  267.     }
  268.     /**
  269.      *得到大結果集記錄數
  270.      *@param out 輸出Statment
  271.      */
  272.     public int GetCount(String Sql) {
  273.         int count = 0;
  274.         if (conn == null) {
  275. //      SaveLog.SetInfo("GetStatment conn NULL", 2);
  276.             conn = ConnectDB();
  277.         }
  278.         ResultSet hjrs = null;
  279.         Statement hjStmt = null;
  280.         try {
  281.             hjStmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, //TYPE_SCROLL_INSENSITIVE
  282.                                           ResultSet.CONCUR_READ_ONLY);
  283.             hjrs = hjStmt.executeQuery(Sql);
  284.             hjrs.first();
  285.             count = hjrs.getInt(1);
  286.             return count;
  287.         }
  288.         catch (Exception e) {
  289.             SaveLog.SetInfo(Sql + " :" + e, 2);
  290.             return 0;
  291.         }
  292.         finally {
  293.             try {
  294.                 if (hjrs != null) {
  295.                     hjrs.close();
  296.                 }
  297.                 if (hjStmt != null) {
  298.                     hjStmt.close();
  299.                 }
  300.             }
  301.             catch (Exception e) {
  302.                 SaveLog.SetInfo(Sql + "close :" + e, 2);
  303.             }
  304.         }
  305.     }
  306.     /**
  307.      *關閉連接
  308.      */
  309.     public void CloseConn() {
  310.         try {
  311.             conn.close();
  312.             conn = null;
  313.         }
  314.         catch (Exception e) {
  315.         }
  316.         finally {
  317.             try {
  318.                 if (conn != null) {
  319.                     conn.close();
  320.                 }
  321.             }
  322.             catch (Exception e) {
  323.             }
  324.         }
  325.     }
  326.     /**
  327.      * 把上傳的文件保存到數據庫的Blob字段中
  328.      * @param instream    輸入的文件流
  329.      * @param table       對應的表名稱
  330.      * @param blobColumn  表中保存文件的Blob字段名稱
  331.      * @param keyColumn   where條件字段名
  332.      * @param keyValue    where條件字段值
  333.      * @throws java.lang.Exception
  334.      */
  335.     public void updateBlob(String xmlStr, //InputStream instream
  336.                            //Connection conn,
  337.                            String table,
  338.                            String blobColumn,
  339.                            String keyColumn,
  340.                            String keyValue) throws SQLException, IOException {
  341.         Statement stmt = null;
  342.         ResultSet rs = null;
  343.         oracle.sql.BLOB blob = null;
  344.         sun.misc.BASE64Decoder base64Decoder = new sun.misc.BASE64Decoder();
  345.         byte b[] = base64Decoder.decodeBuffer(xmlStr);
  346.         InputStream instream = new ByteArrayInputStream(b);
  347.         StringBuffer sqlBuffer = new StringBuffer();
  348.         try {
  349.             conn.setAutoCommit(false);
  350.             sqlBuffer.append("select ");
  351.             sqlBuffer.append(blobColumn);
  352.             sqlBuffer.append(" from ");
  353.             sqlBuffer.append(table);
  354.             sqlBuffer.append(" where ");
  355.             sqlBuffer.append(keyColumn);
  356.             sqlBuffer.append("='");
  357.             sqlBuffer.append(keyValue);
  358.             sqlBuffer.append("' for update ");
  359.             stmt = conn.createStatement();
  360.             rs = (ResultSet) stmt.executeQuery(sqlBuffer.toString());
  361.             if (!rs.next()) {
  362.                 rs.close();
  363.                 stmt.close();
  364.                 throw new IllegalArgumentException(
  365.                     "no record found for keyValue: '" + keyValue + "'");
  366.             }
  367.             blob = (oracle.sql.BLOB) rs.getBlob(1);
  368.             OutputStream outstream = null;
  369.             outstream = blob.getBinaryOutputStream();
  370.             int bufferSize = ( (oracle.sql.BLOB) blob).getBufferSize();
  371.             byte[] buffer = new byte[bufferSize];
  372.             int bytesRead = -1;
  373.             while ( (bytesRead = instream.read(buffer)) != -1) {
  374.                 outstream.write(buffer, 0, bytesRead);
  375.             }
  376.             instream.close();
  377.             outstream.close();
  378.             rs.close();
  379.             stmt.close();
  380.             //System.out.println(bufferSize);
  381.         }
  382.         catch (SQLException e) {
  383.             throw e;
  384.         }
  385.         catch (IOException e) {
  386.             throw e;
  387.         }
  388.     }
  389.     public static void main(String[] args) throws Exception {
  390.         //讀入檢驗XML配置到內存
  391.         System.out.println(MyFunction.DataTimeStr("yyyyMMddHHmmss") + "insert begin!");
  392.         PreparedStatement pstmt = null;
  393.         ResultSet jlRs = null;
  394.         String Sql = "INSERT INTO T_DE_Student (Student_ID,Student_Name,SpellName,UesdName,Class_ID,XBDM_Code,XX_Code,ID_Card,Birthday,MZ_Code,ZZMM_Code,Birth_Code,Birth_Address,Native_Code,IsSingleton,EmigrantCode,IsFloating,Telephone,Status_Code,ResidenceAddress,PostalAddress,PostalCode,Email,HomePageUrl,B_Use,Reason_ID,Reason_Memo,DataSource_ID,Photo,RXFS_Code,RXQ_School,RX_Date,Create_Date,RecordState_ID,HK_Address,JDFS_Code,XSLB_Code,YXX_Code,Number,HealthCode,Nationality) VALUES ('a386b67e-57ec-4765-b6db-01a3523bff4f','陳思園','','','2','0','4','213654789562463','2005-12-21 0:00:00','06','03','120000','','130000','','','','','','','','','','','1','1','轉出','3','','0','','','','','','0','0','0','0','','')";
  395.         Connection conn = null;
  396.            try {
  397.                Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
  398.            }
  399.            catch (java.lang.ClassNotFoundException e) {
  400.            }
  401.            try {
  402.                conn = java.sql.DriverManager.getConnection("jdbc:oracle:oci8:@HBRL""HBRL""HBRL");
  403.                conn.setAutoCommit(false);
  404.            }
  405.            catch (java.sql.SQLException e) {
  406.            }
  407.     try{
  408.         for (int i = 0; i < 10000; i++) {
  409.              pstmt = conn.prepareStatement(Sql);
  410. //            pstmt.setInt(1,1);
  411. //            pstmt.setString(2,"2");
  412. //            pstmt.setString(3,"3");
  413.             pstmt.executeUpdate();
  414.             pstmt.close();
  415.         }
  416.         conn.commit();
  417.     }
  418.     catch(Exception e) {
  419.     }
  420.         System.out.println(MyFunction.DataTimeStr("yyyyMMddHHmmss")+"insert ok!");
  421. /*
  422.         System.out.print("Your writing is successful.");
  423.         System.out.println(MyFunction.DataTimeStr("yyyyMMddHHmmss")+"insert ok!");
  424.             JdbcWork ZzJw = new JdbcWork();
  425.             ResultSet rs = ZzJw.SelectSql(
  426.                 "select rowid,t_czrkjbxx.* from t_czrkjbxx where rownum <= 100000");
  427.             ResultSetMetaData rsmd = rs.getMetaData();
  428.             System.out.println(MyFunction.DataTimeStr("yyyyMMddHHmmss"));
  429.             StringBuffer a = new StringBuffer();
  430.             String b, c;
  431.             int m = 0;
  432.             for (int j = 0; j < 100; j++) {
  433.               for (int i = 1; i <= rsmd.getColumnCount(); i++) {
  434.                 a.append(rsmd.getColumnName(i)).append(rsmd.getColumnTypeName(i)).
  435.                     append(rsmd.
  436.                            getColumnDisplaySize(i));
  437.               }
  438.               rs.next();
  439.               m = m + 1;
  440.             }
  441.             System.out.println(MyFunction.DataTimeStr("yyyyMMddHHmmss") + "  " + m);
  442. */
  443.     }
  444. }
  445. // end class
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章