JDBC + Hibernate writes Blob data to Oracle

Source: Internet
Author: User

The Blob field in Oracle is special. It has much better performance than the long field and can be used to save binary data such as sample slices.
Writing Blob fields is very different from writing other types of fields. Because Blob itself has a cursor, you must use cursor to operate blob. Therefore, before writing Blob, you must obtain the cursor to write data. How can you obtain the Blob cursor?
This requires you to insert an empty blob first, which will create a blob cursor, and then you can query the cursor of the empty blob using select. In this way, you can perform two steps, you can get the blob cursor to write blob data.
Take a look at the following JDBC demo and write the binary file oraclejdbc. jar to the content field of the javatest database table (this is a blob field)
Import java. SQL .*;
Import java. io .*;
Import oracle. SQL .*;
Public class WriteBlob {
Public static void main (String [] args ){
Try {
DriverManager. registerDriver (new oracle. jdbc. driver. OracleDriver ());
Connection conn = DriverManager. getConnection ("jdbc: oracle: thin: @ localhost: 1521: orcl", "fankai", "fankai ");
Conn. setAutoCommit (false );
BLOB blob = null;
PreparedStatement pstmt = conn. prepareStatement ("insert into javatest (name, content) values (?, Empty_blob ())");
Pstmt. setString (1, "fankai ");
Pstmt.exe cuteUpdate ();
Pstmt. close ();
Pstmt = conn. prepareStatement ("select content from javatest where name =? For update ");
Pstmt. setString (1, "fankai ");
ResultSet rset = pstmt.exe cuteQuery ();
If (rset. next () blob = (BLOB) rset. getBlob (1 );
String fileName = "oraclejdbc. jar ";
File f = new File (fileName );
FileInputStream fin = new FileInputStream (f );
System. out. println ("file size =" + fin. available ());
Pstmt = conn. prepareStatement ("update javatest set content =? Where name =? ");
OutputStream out = blob. getBinaryOutputStream ();
Int count =-1, total = 0;
Byte [] data = new byte [(int) fin. available ()];
Fin. read (data );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.