Packagecom.lw.database;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;/*** Create: * Create TABLE Idcard (id char (), pic BLOB); *@authorLiuwei * time:2015 May 25 pm 3:22:26*/ Public classLobtest {protected Static FinalString Default_url = "Jdbc:mysql://127.0.0.1:3306/test?useunicode=true&characterencoding=utf8"; protected Static FinalString driver_name = "Com.mysql.jdbc.Driver"; PrivateConnection Connection =NULL; PublicLobtest ()throwsClassNotFoundException, SQLException {class.forname (driver_name); Connection= Drivermanager.getconnection (Default_url, "User", "password"); } Public voidInsert (String id,string Path)throwsSQLException, IOException {preparedstatement PreparedStatement= Connection.preparestatement ("INSERT into Idcard VALUES (?,?)"); Preparedstatement.setstring (1, id); FileInputStream FileInputStream=NewFileInputStream (path); Preparedstatement.setblob (2, Fileinputstream,fileinputstream.available ()); Preparedstatement.execute (); } Public voidGet (String ID)throwsSQLException, IOException {preparedstatement PreparedStatement= Connection.preparestatement ("Select pic from idcard WHERE id =?")); Preparedstatement.setstring (1, id); ResultSet Results=Preparedstatement.executequery (); while(Results.next ()) {FileOutputStream OutputStream=NewFileOutputStream ("/users/liuwei/temp.png"); InputStream InputStream= Results.getbinarystream (1); intnum =-1; while((Num=inputstream.read ())!=-1) {outputstream.write (num); } outputstream.flush (); Inputstream.close (); Outputstream.close (); } } Public Static voidMain (string[] args)throwsclassnotfoundexception, SQLException, IOException {lobtest test=Newlobtest (); Test.insert ("78907656784323", "/users/liuwei/documents/bt_next_nor.png"); Test.get ("78907656784323"); }}
Attention:
MySQL four types of blobs
Type size (units: bytes)
Tinyblob Max 255B
Blob Max 65K
Mediumblob Max 16M
Longblob Max 4G
When inserting an image, note that the size of the image exceeds the maximum number of bytes that the type can hold.
Insert and read operations for Java BLOB data