Read Blob data through JDBC to demonstrate code
- ImportJava. io. File;
- ImportJava. io. FileOutputStream;
- ImportJava. io. IOException;
- ImportJava. io. InputStream;
- ImportJava. io. OutputStream;
- ImportJava. SQL. Connection;
- ImportJava. SQL. DriverManager;
- ImportJava. SQL. ResultSet;
- ImportJava. SQL. Statement;
- Public ClassJDBC {
- // Public static void main (String [] args) throws Exception {
- //// Write BLOB Data
- //
- /// Obtain the database connection
- // Class. forName ("Oracle. jdbc. driver. OracleDriver ");
- //
- // Connection con = DriverManager. getConnection (
- //
- // "Jdbc: oracle: thin: @ 192.168.0.68: 1521: myOracle", "my", "123 ");
- //
- //// Process the transaction
- //
- // Con. setAutoCommit (false );
- //
- // Statement st = con. createStatement ();
- //
- /// Use the for update method to lock data rows
- //
- // ResultSet rs = st.exe cuteQuery (
- //
- // "Select content from user_content where id = 2 for update ");
- //
- // If (rs. next ()){
- //
- //// Obtain the java. SQL. Blob Object, and Cast is oracle. SQL. BLOB.
- //
- // Oracle. SQL. BLOB blob = (oracle. SQL. BLOB) rs. getBlob (1 );
- //
- //// Output stream to the database
- //
- // OutputStream outStream = blob. getBinaryOutputStream ();
- //
- //// Here, a file is used to simulate the input stream.
- //
- // File file = new File ("d: \ proxy.txt ");
- //
- // InputStream fin = new FileInputStream (file );
- //
- //// Write the input stream to the output stream
- //
- // Byte [] B = new byte [blob. getBufferSize ()];
- //
- // Int len = 0;
- //
- // While (len = fin. read (B ))! =-1 ){
- //
- // OutStream. write (B, 0, len );
- //
- //// Blob. putBytes (1, B );
- //
- //}
- //
- //// Close (pay attention to the Order)
- //
- // Fin. close ();
- //
- // OutStream. flush ();
- //
- // OutStream. close ();
- //
- // Con. commit ();
- //
- // Con. close ();
- //}
- //}
- Public Static VoidMain (String [] args)ThrowsException {
- // Read BLOB Data
- Class. forName ("Oracle. jdbc. driver. OracleDriver");
- Connection con = DriverManager. getConnection (
- "Jdbc: oracle: thin: @ 192.168.0.68: 1521: myOracle","My","123");
- Con. setAutoCommit (False);
- Statement st = con. createStatement ();
- // The SQL statement here does not need "for update"
- ResultSet rs = st.exe cuteQuery (
- "Select content from user_content where id = 2");
- If(Rs. next ()){
- Java. SQL. Blob blob = rs. getBlob (1);
- InputStream ins = blob. getBinaryStream ();
- // Simulate the output stream with a file
- File file =NewFile ("D: \ output.txt");
- OutputStream fout =NewFileOutputStream (file );
- // Write BLOB data to the file below
- Byte[] B =New Byte[1024];
- IntLen =0;
- While(Len = ins. read (B ))! =-1){
- Fout. write (B,0, Len );
- }
- // Close in sequence
- Fout. close ();
- Ins. close ();
- Con. commit ();
- Con. close ();
- }
- }
- }