当前位置:网站首页>MySQL and Oracle processing CLOB and blob fields

MySQL and Oracle processing CLOB and blob fields

2022-06-25 11:04:00 Anonymous & Xiaoyu

MySQL and Oracle In the face of Clob and Blob Field processing




Preface


One 、MySQL And Oracle How the database handles Clob,Blob data type

(1) Not corresponding in the database clob,blob Of the following types :
MySQL in :clob Corresponding text,blob Corresponding blob
DB2/Oracle in :clob Corresponding clob,blob Corresponding blob

(2) domain The corresponding type in :
clob Corresponding String,blob Corresponding byte[]
clob Corresponding java.sql.Clob,blob Corresponding java.sql.Blob

(3) hibernate The corresponding type in the configuration file :
clob–>clob ,blob–>binary
You can also directly use the database to provide types , for example :oracle.sql.Clob,oracle.sql.Blob

Two 、jdbc operation clob( With oracle For example )

1. The insert

First operate clob/blob Unlike operation varchar The type is as simple , The insertion step is generally divided into two steps : The first step is to insert a null value , The second step is to lock the trip , to update clob/blob Field .

// Insert a null value  
conn.setAutoCommit(false);  
String sql = "INSERT INTO T_FILE(NAME, FILE_CONTENT) VALUES ('Jambhala', EMPTY_CLOB())";  
PreparedStatement pstmt = conn.prepareStatement(sql);   
pstmt.executeUpdate();  
// Lock this trip  
String sql_lockstr = "SELECT FILE_CONTENT FROM T_FILE WHERE NAME='Jambhala' FOR UPDATE";  
pstmt = conn.prepareStatement(sql_lockstr);   
ResultSet rs = pstmt.executeQuery();   
oracle.sql.Clob clob = (oracle.sql.Clob)rs.getClob(1);  
java.io.OutputStream writer = clob.getAsciiOutputStream();   
byte[] temp = newFileContent.getBytes();   
writer.write(temp);   
writer.flush();   
writer.close();  
pstmt.close();  

2. Read operation

The code is as follows ( Example ):

oracle.sql.Clob clob = rs.getClob("FILE_CONTENT");  
if(clob != null){
      
    Reader is = clob.getCharacterStream();  
    BufferedReader br = new BufferedReader(is);  
    String s = br.readLine();  
    while(s != null){
      
        content += s+"<br>";  
        s = br.readLine();  
    }  
}  

3、 ... and 、jdbc operation blob

conn.setAutoCommit(false);  
String sql = "INSERT INTO T_PHOTO(NAME, PHOTO) VALUES ('Jambhala', EMPTY_BLOB())";  
pstmt = conn.prepareStatement(sql);   
pstmt = conn.executeUpdate();  
sql = "SELECT PHOTO FROM T_PHOTO WHERE NAME='Jambhala'";  
pstmt = conn.prepareStatement(sql);   
rs = pstmt.executeQuery(sql);  
if(rs.next()){
      
   oracle.sql.Blob blob = (oracle.sql.Blob)rs.getBlob(1);  
}  
//write to a file 
File file=new File("C:\\test.rar");  
FileInputStream fin = new FileInputStream(file);  
OutputStream out = blob.getBinaryOutputStream();  
int count=-1,total=0;  
byte[] data = new byte[blob.getBufferSize()];  
while((count=fin.read(data)) != -1){
      
   total += count;  
   out.write(data, 0, count);  
}   

Four 、hibernate Handle clob

MyFile file = new MyFile();  
file.setName("Jambhala");  
file.setContent(Hibernate.createClob(""));  
session.save(file);  
session.flush();  
session.refresh(file, LockMode.UPGRADE);  
oracle.sql.Clob clob = (oracle.sql.Clob)file.getContent();  
Writer pw = clob.getCharacterOutputStream();  
pw.write(longText);   // Write long text  
pw.close();  
session.close();  

5、 ... and 、 Use hibernate Handle blob

The principle is basically the same :

Photo photo = new Photo();  
photo.setName("Jambhala");  
photo.setPhoto(Hibernate.createBlob(""));  
session.save(photo);  
session.flush();  
  
session.refresh(photo, LockMode.UPGRADE);  // Lock this object  
oracle.sql.Blob blob = photo.getPhoto();   // Get this blob The pointer to  
OutputStream out = blob.getBinaryOutputStream();  
// Write a file  
File f = new File("C:\\test.rar");  
FileInputStream fin = new FileInputStream(f);  
int count=-1,total=0;  
byte[] data = new byte[(int)fin.available()];  
out.write(data);  
fin.close();  
out.close();  
session.flush();  
  
  
String DRIVER = "oracle.jdbc.driver.OracleDriver";  
//Oracle For connection URL 
private static final String URL = "jdbc:oracle:thin:@testora:1521:orac";  
// user name  
private static final String USER = "scott";  
// password  
private static final String PASSWORD = "pswd";  
// Database connection  
private static Connection conn = null;  
//SQL Statement object  
private static Statement stmt = null;  
//@roseuid 3EDA089E02BC 
public LobPros(){
    }  
  
// Insert a new... Into the database Clob object  
//@param infile  Data files  
//@throws java.lang.Exception 
//@roseuid 3EDA089E02BC 
public static void clobInsert(String infile) throws Exception {
      
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();   
   conn.setAutoCommit(false);  
   try{
      
    // Insert an empty Clob object  
        stmt.executeUpdate("INSERT INTO TEST_CLOB VALUES ('111', EMPTY_CLOB())");  
        // Query the Clob Object and lock  
        ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM TEST_CLOB WHERE ID='111' FOR UPDATE");  
        while(rs.next()){
      
       // Remove this Clob object  
           oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob("CLOBCOL");  
           // towards Clob Object  
           BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());   
           BufferedReader in = new BufferedReader(new FileReader(infile));  
           int c;  
           while((c=in.read()) != -1){
      
          out.write(c);  
           }  
           in.close();  
           out.close();  
        }  
        // Formal submission  
        conn.commit();  
   }catch(Exception e){
      
      // Error rollback  
      conn.rollback();  
      throw e;  
   }  
  
   // Restore the original submission status  
   conn.setAutoCommit(defaultCommit);  
}  
  
// modify Clob object ( It's in the original Clob Based on the object ) 
//@param infile  Data files  
//@throws java.lang.Exception 
//@roseuid 3EDA089E02BC 
public static void clobModify(String infile) throws Exception {
      
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();   
   conn.setAutoCommit(false);  
   try{
      
    // Inquire about Clob Object and lock  
        ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM TEST_CLOB WHERE ID='111' FOR UPDATE");  
        while(rs.next()){
      
       // Access to this Clob object  
           oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob("CLOBCOL");  
           // Make overwriting changes  
           BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());   
           BufferedReader in = new BufferedReader(new FileReader(infile));   
           int c;  
           while ((c=in.read())!=-1) {
       
              out.write(c);   
           }   
           in.close();   
           out.close();   
        }  
        // Formal submission  
        conn.commit();  
   }catch(Exception e){
      
      // Error rollback  
      conn.rollback();  
      throw e;  
   }  
   // Restore the original submission status  
   conn.setAutoCommit(defaultCommit);  
}  
  
// Replace CLOB object ( The original CLOB Object cleanup , Replace it with a brand new one CLOB object  
//@param infile  Data files  
//@throws java.lang.Exception 
//@roseuid 3EDA04BF01E1 
public static void clobReplace(String infile) throws Exception {
      
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();  
   conn.setAutoCommit(false);  
   try{
      
    // Empty original CLOB object  
        stmt.executeUpdate("UPDATE TEST_CLOB SET CLOBCOL=EMPTY_CLOB() WHERE ID='111'");  
        // Inquire about CLOB Object and lock  
        ResultSet rs = stmt.executeQuery("SELECT CLOBCOL FROM TEST_CLOB WHERE ID='111' FOR UPDATE");  
        while (rs.next()) {
      
       // Access to this CLOB object  
           oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob("CLOBCOL");  
           // Update data  
           BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());  
           BufferedReader in = new BufferedReader(new FileReader(infile));   
           int c;  
           while ((c=in.read())!=-1) {
       
          out.write(c);   
       }   
       in.close();   
       out.close();  
        }  
    // Formal submission  
    conn.commit();  
   }catch(Exception e){
      
    // Error rollback  
    conn.rollback();   
    throw e;  
   }  
   // Restore the original submission status  
   conn.setAutoCommit(defaultCommit);  
}  
  
//CLOB Object read  
//@param outfile  Output file name  
//@throws java.lang.Exception 
//@roseuid 3EDA04D80116 
public static void clobRead(String outfile) throws Exception {
      
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();  
   conn.setAutoCommit(false);  
   try{
      
        // Inquire about CLOB object  
        ResultSet rs = stmt.executeQuery("SELECT * FROM TEST_CLOB WHERE ID='111'");  
        while (rs.next()) {
      
       // obtain CLOB object  
           oracle.sql.CLOB clob = (oracle.sql.CLOB)rs.getClob("CLOBCOL");  
           // Output in character form  
           BufferedReader in = new BufferedReader(clob.getCharacterStream());   
           BufferedWriter out = new BufferedWriter(new FileWriter(outfile));   
           int c;  
           while ((c=in.read())!=-1) {
      
              out.write(c);  
           }  
       out.close();   
       in.close();  
        }  
   }catch(Exception e){
      
       conn.rollback();   
       throw e;  
   }  
   // Restore the original submission status  
   conn.setAutoCommit(defaultCommit);  
}  
  
// Insert a new... Into the database BLOB object  
//@param infile  Data files  
//@throws java.lang.Exception 
//@roseuid 3EDA04E300F6 
public static void blobInsert(String infile) throws Exception {
       
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();   
   conn.setAutoCommit(false);   
   try {
       
    // Insert an empty BLOB object  
    stmt.executeUpdate("INSERT INTO TEST_BLOB VALUES ('222', EMPTY_BLOB())");   
    // Query the BLOB Object and lock  
    ResultSet rs = stmt.executeQuery("SELECT BLOBCOL FROM TEST_BLOB WHERE ID='222' FOR UPDATE");   
    while (rs.next()) {
       
       // Remove this BLOB object  
       oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("BLOBCOL");   
       // towards BLOB Object  
       BufferedOutputStream out = new BufferedOutputStream(blob.getBinaryOutputStream());   
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(infile));   
       int c;   
       while ((c=in.read())!=-1) {
       
        out.write(c);   
       }   
       in.close();   
       out.close();   
    }   
    // Formal submission  
    conn.commit();   
    } catch (Exception e) {
       
    // Error rollback  
    conn.rollback();   
    throw e;   
    }   
    // Restore the original submission status  
    conn.setAutoCommit(defaultCommit);   
}   
  
// modify BLOB object ( It's in the original BLOB Based on the object ) 
//@param infile  Data files  
//@throws java.lang.Exception 
//@roseuid 3EDA04E90106 
public static void blobModify(String infile) throws Exception {
       
    // Set not to submit automatically  
    boolean defaultCommit = conn.getAutoCommit();   
    conn.setAutoCommit(false);   
    try {
       
    // Inquire about BLOB Object and lock  
    ResultSet rs = stmt.executeQuery("SELECT BLOBCOL FROM TEST_BLOB WHERE ID='222' FOR UPDATE");   
    while (rs.next()) {
       
       // Remove this BLOB object  
       oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("BLOBCOL");   
       // towards BLOB Object  
       BufferedOutputStream out = new BufferedOutputStream(blob.getBinaryOutputStream());   
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(infile));   
       int c;   
       while ((c=in.read())!=-1) {
       
          out.write(c);   
       }   
       in.close();   
       out.close();   
    }   
    // Formal submission  
    conn.commit();   
    } catch (Exception e) {
       
    // Error rollback  
    conn.rollback();   
    throw e;   
    }   
    // Restore the original submission status  
    conn.setAutoCommit(defaultCommit);   
}   
  
// Replace BLOB object ( The original BLOB Object cleanup , Replace it with a brand new one BLOB object ) 
//@param infile  Data files  
//@throws java.lang.Exception 
//@roseuid 3EDA0505000C 
public static void blobReplace(String infile) throws Exception {
       
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();   
   conn.setAutoCommit(false);   
   try {
       
    // Empty original BLOB object  
    stmt.executeUpdate("UPDATE TEST_BLOB SET BLOBCOL=EMPTY_BLOB() WHERE ID='222'");   
    // Query the BLOB Object and lock  
    ResultSet rs = stmt.executeQuery("SELECT BLOBCOL FROM TEST_BLOB WHERE ID='222' FOR UPDATE");   
    while (rs.next()) {
       
       // Remove this BLOB object  
       oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("BLOBCOL");   
       // towards BLOB Object  
       BufferedOutputStream out = new BufferedOutputStream(blob.getBinaryOutputStream());   
       BufferedInputStream in = new BufferedInputStream(new FileInputStream(infile));   
       int c;   
       while ((c=in.read())!=-1) {
       
          out.write(c);   
       }   
       in.close();   
       out.close();   
        }   
    // Formal submission  
    conn.commit();   
   } catch (Exception e) {
       
    // Error rollback  
    conn.rollback();   
    throw e;   
   }   
   // Restore the original submission status  
   conn.setAutoCommit(defaultCommit);   
}   
  
//BLOB Object read  
//@param outfile  Output file name  
//@throws java.lang.Exception 
//@roseuid 3EDA050B003B 
public static void blobRead(String outfile) throws Exception {
       
   // Set not to submit automatically  
   boolean defaultCommit = conn.getAutoCommit();   
   conn.setAutoCommit(false);   
   try {
       
         // Inquire about BLOB object  
     ResultSet rs = stmt.executeQuery("SELECT BLOBCOL FROM TEST_BLOB WHERE ID='222'");   
     while (rs.next()) {
       
        // Remove this BLOB object  
        oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("BLOBCOL");   
        // Output in binary form  
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outfile));   
        BufferedInputStream in = new BufferedInputStream(blob.getBinaryStream());   
        int c;   
        while ((c=in.read())!=-1) {
       
           out.write(c);   
            }   
        in.close();   
        out.close();   
         }   
     // Formal submission  
         conn.commit();   
   } catch (Exception e) {
       
    // Error rollback  
    conn.rollback();   
    throw e;   
   }   
   // Restore the original submission status  
   conn.setAutoCommit(defaultCommit);   
}   
  
// Create test forms  
//@throws Exception 
public static void createTables() throws Exception {
       
   try {
       
    stmt.executeUpdate("CREATE TABLE TEST_CLOB (ID NUMBER(3), CLOBCOL CLOB)");   
    stmt.executeUpdate("CREATE TABLE TEST_BLOB (ID NUMBER(3), BLOBCOL BLOB)");   
   } catch (Exception e) {
     }   
}   
  
//@param args -  Command line arguments  
//@throws java.lang.Exception 
//@roseuid 3EDA052002AC 
public static void main(String[] args) throws Exception {
       
   // Loading drive , Establish a database connection  
   Class.forName(DRIVER);   
   conn = DriverManager.getConnection(URL,USER,PASSWORD);   
   stmt = conn.createStatement();   
   // Set up test forms  
   createTables();   
   //CLOB Object insertion test  
   clobInsert("c:/clobInsert.txt");   
   clobRead("c:/clobInsert.out");   
   //CLOB Object modification test  
   clobModify("c:/clobModify.txt");   
   clobRead("c:/clobModify.out");   
   //CLOB Object replacement test  
   clobReplace("c:/clobReplace.txt");   
   clobRead("c:/clobReplace.out");   
   //BLOB Object insertion test  
   blobInsert("c:/blobInsert.doc");   
   blobRead("c:/blobInsert.out");   
   //BLOB Object modification test  
   blobModify("c:/blobModify.doc");   
   blobRead("c:/blobModify.out");   
   //BLOB Object replacement test  
   blobReplace("c:/blobReplace.doc");   
   blobRead("c:/bolbReplace.out");   
   // Close resource exit  
   conn.close();   
   System.exit(0);   
}  

summary

原网站

版权声明
本文为[Anonymous & Xiaoyu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200540219255.html