jdbc操作oracleのblobフィールド


直接コードを貼りました
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestBlob {
	public void insertBlob() throws ClassNotFoundException, SQLException, IOException
	{
	     //  JDBC       
	    Class.forName("oracle.jdbc.driver.OracleDriver");
	      Connection con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.95:1521:sttri", "ivm", "ivm123");
	      con.setAutoCommit(false);
	      Statement st = con.createStatement();
	      //       empty_blob()
	      st.executeUpdate("insert into TESTBLOB (ID, testlob) values (255, empty_blob())");
	      //         ,  “for update”  
	    ResultSet rs = st.executeQuery("select testlob from TESTBLOB where ID=255 for update");
	      OutputStream outStream = null;
	      File f = new File("1.png");
	      FileInputStream fi = new FileInputStream(f);
	     int flength = (int)f.length();
	     byte[] data = new byte[flength];
	     fi.read(data);
	    if (rs.next())
	    {
	        //  java.sql.Blob        oracle.sql.BLOB
	        oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob("testlob");
	        outStream = blob.getBinaryOutputStream();
	        //data    byte  ,  :byte[] data
	        outStream.write(data, 0, data.length);
	    }
	    if(outStream!=null)
	    {
	    	outStream.flush();
	        outStream.close();
	    }
	    if(con!=null)
	    {
	    	con.commit();
	        con.close();
	    }
	}
	
	public byte[] readBlob() throws ClassNotFoundException, SQLException, IOException
	{
		//       
	    //  JDBC       
	    Class.forName("oracle.jdbc.driver.OracleDriver");
	    Connection con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.95:1521:sttri", "ivm", "ivm123");
	    con.setAutoCommit(false);
	    Statement st = con.createStatement();
	    //   “for update”
	    ResultSet rs = st.executeQuery("select testlob from TESTBLOB where ID=255");
	    byte[] data = null;
	    InputStream inStream = null;
	    if (rs.next())
	    {
	        java.sql.Blob blob = rs.getBlob("testlob");
	        inStream = blob.getBinaryStream();
	        //data           ,   byte[]
	        data = new byte[(int)blob.length()];
	        inStream.read(data);
	        inStream.close();
	    }
	    if(inStream!=null)
	    {
	    	 inStream.close();
	    }
	    if(con!=null)
	    {
	    	con.commit();
	    	con.close();
	    }
	    FileOutputStream fo = new FileOutputStream("1  .png");
	    fo.write(data);
	    return data;
	}
	


	
	public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException
	{
		//blob  
		new TestBlob().insertBlob();
		//blob  
		new TestBlob().readBlob();
	}
}