Code:
- Import java. Io .*;
- Import java. SQL .*;
- /**
- * Test the BLOB data operation.
- */
- Public class blobtest {
- Connection con = NULL;
- Private Static string filepath = "D:/test/smile.jpg ";
- Private Static string fileoutpath = "D:/test/smilecopy.jpg ";
- /**
- * Add BLOB data to the database
- */
- Public void addblob (){
- Try {
- // Create a preparedstatement instance
- Preparedstatement pstmt = con
- . Preparestatement ("insert into blobtest values (1 ,?) ");
- File file = new file (filepath );
- Fileinputstream FCM = new fileinputstream (File );
- // Set the input stream as the object of the preprocessing statement.
- Pstmt. setbinarystream (1, FS, (INT) file. Length ());
- // Execute update
- Pstmt.exe cuteupdate ();
- Pstmt. Close ();
- FCM. Close ();
- } Catch (Exception e ){
- E. printStackTrace ();
- }
- }
- /**
- * Create a table
- */
- Public void createTable (){
- Try {
- Con.createstatement(cmd.exe cute (
- "Create table blobtest (ID int, PIC blob ,"
- + "Constraint pk_blobtest primary key (ID ));");
- } Catch (exception e ){
- E. printstacktrace ();
- }
- }
- /**
- * Reading BLOB data from the database
- */
- Public void getblob (){
- Try {
- // Create a statement instance
- Statement stmt = con. createstatement ();
- Resultset rst = stmt
- . Executequery ("select * From blobtest where id = 1 ");
- RST. Next ();
- // Obtain BLOB data and its input stream, and then write the data to the file through the input stream.
- Blob blob = RST. getblob ("pic ");
- Fileoutputstream out = new fileoutputstream (new file (
- Fileoutpath ));
- Inputstream in = blob. getbinarystream ();
- Int I;
- While (I = in. Read ())! =-1)
- Out. Write (I );
- // Close the input and output streams.
- In. Close ();
- Out. Close ();
- } Catch (exception e ){
- E. printstacktrace ();
- }
- }
- Public static void main (string [] ARGs) throws exception {
- Class. forname ("com. MySQL. JDBC. Driver"). newinstance ();
- Blobtest test = new blobtest ();
- Test. Con = java. SQL. drivermanager. getconnection (
- "JDBC: mysql: // localhost: 3306/test", "root", "123456 ");
- Test. createtable ();
- Test. addblob ();
- Test. getblob ();
- }
- }
MySQL has four blob types:
· Tinyblob: Only 255 characters long
· BLOB: up to KB
· Mediumblob: up to 16 MB bytes
· Longblob: up to 4 GB