package examples.jdbc.oracle;
import java.sql.*;
import java.io.*;
import weblogic.jdbc.common.*;
import weblogic.jdbc.common.*;
import java.util.Properties;
public class OracleBlobClob {
  
  public static void main(String argv[])
  {
    String user = "scott";
    String password = "tiger";
    String server = "DEMO";    try {
      for (int i = 0; i < argv.length; i++) 
      {
        if (argv[i].equals("-user")) {
          i++; 
          user = (argv[i].equals("null") ? "" : argv[i]);
        } 
        else if (argv[i].equals("-password")) {
          i++; 
          password = (argv[i].equals("null") ? "" : argv[i]);
        }
        else if (argv[i].equals("-server")) {
          i++; 
          server = (argv[i].equals("null") ? "" : argv[i]);
        }
      }
    } catch(ArrayIndexOutOfBoundsException aiobe) {
      System.err.println("\nUsage: java examples.jdbc.oracle.OracleBlobClob [options] \n\n" +
                         "where options include:\n" +
                         "    -user <user>            User name to be passed to database.\n" +
                         "    -password <password>    User password to be passed to database.\n" +
                         "    -server <server>        DNS name of database server.\n"); 
      System.exit(1);
    }    java.sql.Blob myBlob     = null;
    java.sql.Clob myClob     = null;
    java.sql.Connection conn = null;    // get a connection to the Oracle DBMS
    // substitute the name of the machine hosting your 
    //  Oracle server for myOracle8Server    Properties props = new Properties();
    props.put("user",     user);
    props.put("password", password);
    props.put("server",   server);    try {
      Driver myDriver = (Driver)
          Class.forName("weblogic.jdbc.oci.Driver").newInstance();
      conn = myDriver.connect("jdbc:weblogic:oracle" , props);
            // set Oracle's Auto Commit feature to false. 
      // This is necessary when manipulating Blobs and Clobs.
      conn.setAutoCommit(false);      // ============== Create Table ==================
      // Create a table with a Blob and Clob column
      try {
          // if table does not exist, create it. 
          Statement crstmt = conn.createStatement();
          System.out.println("\nCreating table with Blobs and Clobs...");
          crstmt.execute("create table lobtest (id int, blobcol Blob, clobcol Clob)");
          crstmt.close();
      }
      catch (Exception e) {
          System.out.println("Exception: " + e);
          System.out.println("Table already exists. Dropping it and re-creating...");
          Statement crstmt2 = conn.createStatement();
          crstmt2.execute("drop table lobtest");
          crstmt2.execute("create table lobtest (id int, blobcol Blob, clobcol Clob)");
          crstmt2.close();
      }
      System.out.println("Table created.");
      // ============== Initializing blob and clob values ==================
      Statement stmt = conn.createStatement();
      System.out.println("\nInserting row with blank blob and clob columns...");
      stmt.execute("insert into lobtest values (44,EMPTY_BLOB(),EMPTY_CLOB())");
      System.out.println("Row has been inserted.");      // ============== Manipulating the Blob column ======================
      // get a reference to the Blob column
      stmt.execute("select * from lobtest where id=44");
      ResultSet rs = stmt.getResultSet();
      while ( rs.next() ) {
          myBlob = rs.getBlob("blobcol");
      }      // Create a byte array and store some data in it
      System.out.println("\nCreating the following byte array:");
      int STREAM_SIZE = 10;
      byte[] b = new byte[STREAM_SIZE];
      for (int i=0; i < STREAM_SIZE; i++) {
          b[i] = (byte)(40 + (i%20)); // range 40-60
          System.out.println("byte[" + i + "] = " + b[i]);         
      }      // Write the byte array to a stream and store it in the Blob column
      System.out.println
          ("\nWriting the byte array to a stream" +
           " and storing it in the table as a blob...");
      InputStream is = new ByteArrayInputStream(b);
      java.io.OutputStream os =
          ((weblogic.jdbc.common.OracleBlob) myBlob).getBinaryOutputStream();
      byte[] inBytes = new byte[STREAM_SIZE]; 
      int numBytes = is.read(inBytes);
      
      // write the input stream to the output stream
      while (numBytes > 0) {
          os.write(inBytes, 0, numBytes);
          numBytes = is.read(inBytes);
      }
      // The flush() method causes the data to be written to the table
      os.flush();      //  read back the blob
      System.out.println("\nReading the blob back from the table and displaying:");
      Statement readblob = conn.createStatement();
      readblob.execute("select * from lobtest where id=44");
      ResultSet rsreadblob = readblob.getResultSet();      // read the blob into a byte array and display
      byte[] r = new byte[STREAM_SIZE];
      while ( rsreadblob.next() ) { 
          Blob myReadBlob =  rsreadblob.getBlob("blobcol");
          java.io.InputStream readis = myReadBlob.getBinaryStream();
          for (int i=0 ; i < STREAM_SIZE ; i++) {
              r[i] = (byte) readis.read();
              System.out.println("output [" + i + "] = " + r[i]);
          }
      }
      
      
      // create some character data to work with
      String ss = "abcdefghijklmnopqrstuvwxyz";
      System.out.println("\nCreated the following string to be stored as a clob:\n" +
                         ss);
      
      // ============== Manipulating the Clob column ======================
      // get a reference to the clob column
      stmt.execute("select * from lobtest where id=44");
      ResultSet crs = stmt.getResultSet();
      while ( crs.next() ) {
          myClob = crs.getClob("clobcol");
          
          java.io.OutputStream osss =
              ((weblogic.jdbc.common.OracleClob) myClob).getAsciiOutputStream();
          byte[] bss = ss.getBytes("ASCII");
          osss.write(bss);
          osss.flush();
      }
      conn.commit();
      
      // read back the clob
      System.out.println("\nReading the clob back from the table and displaying:");
      Statement readclob = conn.createStatement();
      readclob.execute("select * from lobtest where id=44");
      ResultSet rsreadclob = readclob.getResultSet();
            
      // read the clob in as and ASCII stream, write to a character array, and display
      while ( rsreadclob.next() ) { 
          Clob myReadClob =rsreadclob.getClob("clobcol");    
          java.io.InputStream readClobis = myReadClob.getAsciiStream();
          char[] c = new char[26];
          for (int i=0 ; i < 26  ; i++) {
              c[i] = (char) readClobis.read();
              System.out.println("output [" + i + "] = " + c[i]);
          }
      }        
                
      // Drop the table and clean up connections
      System.out.println("\nDropping table...");
      Statement dropstmt = conn.createStatement();
      dropstmt.execute("drop table lobtest");
      System.out.println("Table dropped.");
      
    } catch (Exception e) {
        System.out.println("Exception was thrown: " + e.getMessage());
    } finally {
        try {
          if (conn != null)
            conn.close();
        } catch (SQLException sqle) {
            System.out.println("SQLException was thrown: " + sqle.getMessage());
        }
    }
  }
    
}

解决方案 »

  1.   

    package examples.jdbc.oracle;
    import java.sql.*;
    import java.io.*;
    import weblogic.jdbc.common.*;
    import weblogic.jdbc.common.*;
    import java.util.Properties;
    public class OracleBlobClob {
      
      public static void main(String argv[])
      {
        String user = "scott";
        String password = "tiger";
        String server = "DEMO";    try {
          for (int i = 0; i < argv.length; i++) 
          {
            if (argv[i].equals("-user")) {
              i++; 
              user = (argv[i].equals("null") ? "" : argv[i]);
            } 
            else if (argv[i].equals("-password")) {
              i++; 
              password = (argv[i].equals("null") ? "" : argv[i]);
            }
            else if (argv[i].equals("-server")) {
              i++; 
              server = (argv[i].equals("null") ? "" : argv[i]);
            }
          }
        } catch(ArrayIndexOutOfBoundsException aiobe) {
          System.err.println("\nUsage: java examples.jdbc.oracle.OracleBlobClob [options] \n\n" +
                             "where options include:\n" +
                             "    -user <user>            User name to be passed to database.\n" +
                             "    -password <password>    User password to be passed to database.\n" +
                             "    -server <server>        DNS name of database server.\n"); 
          System.exit(1);
        }    java.sql.Blob myBlob     = null;
        java.sql.Clob myClob     = null;
        java.sql.Connection conn = null;    // get a connection to the Oracle DBMS
        // substitute the name of the machine hosting your 
        //  Oracle server for myOracle8Server    Properties props = new Properties();
        props.put("user",     user);
        props.put("password", password);
        props.put("server",   server);    try {
          Driver myDriver = (Driver)
              Class.forName("weblogic.jdbc.oci.Driver").newInstance();
          conn = myDriver.connect("jdbc:weblogic:oracle" , props);
                // set Oracle's Auto Commit feature to false. 
          // This is necessary when manipulating Blobs and Clobs.
          conn.setAutoCommit(false);      // ============== Create Table ==================
          // Create a table with a Blob and Clob column
          try {
              // if table does not exist, create it. 
              Statement crstmt = conn.createStatement();
              System.out.println("\nCreating table with Blobs and Clobs...");
              crstmt.execute("create table lobtest (id int, blobcol Blob, clobcol Clob)");
              crstmt.close();
          }
          catch (Exception e) {
              System.out.println("Exception: " + e);
              System.out.println("Table already exists. Dropping it and re-creating...");
              Statement crstmt2 = conn.createStatement();
              crstmt2.execute("drop table lobtest");
              crstmt2.execute("create table lobtest (id int, blobcol Blob, clobcol Clob)");
              crstmt2.close();
          }
          System.out.println("Table created.");
          // ============== Initializing blob and clob values ==================
          Statement stmt = conn.createStatement();
          System.out.println("\nInserting row with blank blob and clob columns...");
          stmt.execute("insert into lobtest values (44,EMPTY_BLOB(),EMPTY_CLOB())");
          System.out.println("Row has been inserted.");      // ============== Manipulating the Blob column ======================
          // get a reference to the Blob column
          stmt.execute("select * from lobtest where id=44");
          ResultSet rs = stmt.getResultSet();
          while ( rs.next() ) {
              myBlob = rs.getBlob("blobcol");
          }      // Create a byte array and store some data in it
          System.out.println("\nCreating the following byte array:");
          int STREAM_SIZE = 10;
          byte[] b = new byte[STREAM_SIZE];
          for (int i=0; i < STREAM_SIZE; i++) {
              b[i] = (byte)(40 + (i%20)); // range 40-60
              System.out.println("byte[" + i + "] = " + b[i]);         
          }      // Write the byte array to a stream and store it in the Blob column
          System.out.println
              ("\nWriting the byte array to a stream" +
               " and storing it in the table as a blob...");
          InputStream is = new ByteArrayInputStream(b);
          java.io.OutputStream os =
              ((weblogic.jdbc.common.OracleBlob) myBlob).getBinaryOutputStream();
          byte[] inBytes = new byte[STREAM_SIZE]; 
          int numBytes = is.read(inBytes);
          
          // write the input stream to the output stream
          while (numBytes > 0) {
              os.write(inBytes, 0, numBytes);
              numBytes = is.read(inBytes);
          }
          // The flush() method causes the data to be written to the table
          os.flush();      //  read back the blob
          System.out.println("\nReading the blob back from the table and displaying:");
          Statement readblob = conn.createStatement();
          readblob.execute("select * from lobtest where id=44");
          ResultSet rsreadblob = readblob.getResultSet();      // read the blob into a byte array and display
          byte[] r = new byte[STREAM_SIZE];
          while ( rsreadblob.next() ) { 
              Blob myReadBlob =  rsreadblob.getBlob("blobcol");
              java.io.InputStream readis = myReadBlob.getBinaryStream();
              for (int i=0 ; i < STREAM_SIZE ; i++) {
                  r[i] = (byte) readis.read();
                  System.out.println("output [" + i + "] = " + r[i]);
              }
          }
          
          
          // create some character data to work with
          String ss = "abcdefghijklmnopqrstuvwxyz";
          System.out.println("\nCreated the following string to be stored as a clob:\n" +
                             ss);
          
          // ============== Manipulating the Clob column ======================
          // get a reference to the clob column
          stmt.execute("select * from lobtest where id=44");
          ResultSet crs = stmt.getResultSet();
          while ( crs.next() ) {
              myClob = crs.getClob("clobcol");
              
              java.io.OutputStream osss =
                  ((weblogic.jdbc.common.OracleClob) myClob).getAsciiOutputStream();
              byte[] bss = ss.getBytes("ASCII");
              osss.write(bss);
              osss.flush();
          }
          conn.commit();
          
          // read back the clob
          System.out.println("\nReading the clob back from the table and displaying:");
          Statement readclob = conn.createStatement();
          readclob.execute("select * from lobtest where id=44");
          ResultSet rsreadclob = readclob.getResultSet();
                
          // read the clob in as and ASCII stream, write to a character array, and display
          while ( rsreadclob.next() ) { 
              Clob myReadClob =rsreadclob.getClob("clobcol");    
              java.io.InputStream readClobis = myReadClob.getAsciiStream();
              char[] c = new char[26];
              for (int i=0 ; i < 26  ; i++) {
                  c[i] = (char) readClobis.read();
                  System.out.println("output [" + i + "] = " + c[i]);
              }
          }        
                    
          // Drop the table and clean up connections
          System.out.println("\nDropping table...");
          Statement dropstmt = conn.createStatement();
          dropstmt.execute("drop table lobtest");
          System.out.println("Table dropped.");
          
        } catch (Exception e) {
            System.out.println("Exception was thrown: " + e.getMessage());
        } finally {
            try {
              if (conn != null)
                conn.close();
            } catch (SQLException sqle) {
                System.out.println("SQLException was thrown: " + sqle.getMessage());
            }
        }
      }
        
    }