Blob types in 1.MySQL
MySQL can store large file data, commonly used BLOB objects . Films, videos and more.
BLOB is a binary large object that can hold a variable amount of data. Because it is a binary object, it is independent of the encoding method . There are 4 types of blobs :tinyblob,blobs, Mediumblob and longblob. They can only accommodate the maximum length of a value differently.
The maximum length to save for four field types is as follows:
TINYBLOB-255 bytes
BLOB-65535 bytes (64KB)
mediumblob-16,777,215 bytes (16MB) (2^24-1)
longblob-4g bytes (2^32–1)
2.java reading of MySQL images
The following is the Phototest table structure defined in the test database.
| Id |
Int (11) |
YES |
| Photo |
Mediumblob |
YES |
The code to save and read the picture is as follows:
1 ImportJava.io.*;2 ImportJava.sql.*;3 Public classLoadstoreblob {4 Public Static voidMain (string[] args) {5DBConnection DB =NewDBConnection ();//the class that is responsible for connecting to the MySQL database6Connection con =NULL;7PreparedStatement PS =NULL;8ResultSet rs =NULL;9InputStream in =NULL; Ten Try { One //read a picture from a local hard drive to a database Acon=db.getconn (); -in=NewFileInputStream ("Sdf.png"); -Ps=con.preparestatement ("INSERT into test.phototest values (?,?)"); thePs.setint (); -Ps.setbinarystream (2, in, in.available ()); - ps.executeupdate (); - in.close (); + db.closeconn (con); - + //read pictures from the database save to local hard disk Acon=db.getconn (); atPs=con.preparestatement ("select * from Test.phototest where id=?")); -Ps.setint (); -rs=ps.executequery (); -Rs.next ();//point the cursor to the first row -In=rs.getbinarystream ("Photo"); - byte[] b=New byte[In.available ()];//new byte array to save picture data in In.read (b); -OutputStream out=NewFileOutputStream ("222.jpg"); to Out.write (b); + Out.flush (); - out.close (); the db.closeconn (con); * } $ Catch(Exception e) {Panax NotoginsengSystem.out.println ("Error::" +e); - } the } +}
3. Select the appropriate field size
If the maximum length of the selected field type is smaller, the saved data is not available, and the MySQL data truncation exception may be reported. Such as:
Com.mysql.jdbc.MysqlDataTruncation:Data Truncation:data too long for column ' photo ' at row 1
Mysql Chinese Reference manual Column type:
Http://dev.mysql.com/doc/refman/5.1/zh/column-types.html#blob