Package example;
Import java. Io .*;
Import java. SQL .*;
Public class test {
Public static void main (string [] ARGs) throws exception {
// Write ();
Read ();
}
Public static void write () throws exception {
Connection connection = getconnection ();
If (connection = NULL ){
Return;
}
String SQL = "insert into T2 (PIC) values (?) ";
String filepath = "/mnt/hda6/doc/flower2.jpg ";
Fileinputstream FCM = new fileinputstream (filepath );
Preparedstatement PST = connection. preparestatement (SQL );
Pst. setbinarystream (1, fiis, fiis. Available ());
Pst.exe cute ();
Pst. Close ();
Pst. Close ();
}
Public static void read () throws exception {
Connection connection = getconnection ();
If (connection = NULL ){
Return;
}
String SQL = "select pic from t2 ";
Statement ST = connection. createstatement ();
Resultset rs = st.exe cutequery (SQL );
Byte [] buffer = new byte [1024];
While (Rs. Next ()){
Blob B = Rs. getblob ("pic ");
Int size = (INT) B. Length ();
Inputstream IPS = B. getbinarystream ();
Fileoutputstream Fos = new fileoutputstream ("/home/x.jpg ");
While (size = IPs. Read (buffer ))! =-1 ){
FOS. Write (buffer, 0, size );
}
FOS. Close ();
IPS. Close ();
}
Rs. Close ();
St. Close ();
Connection. Close ();
}
Public static connection getconnection (){
Connection connection = NULL;
Try {
String driverclass = "com. MySQL. JDBC. Driver ";
String url = "JDBC: mysql: // localhost/mydb? Useunicode = true & characterencoding = GBK ";
String user = "root ";
String Password = "";
Class. forname (driverclass );
Connection = drivermanager. getconnection (URL, user, password );
} Catch (exception e ){
E. printstacktrace ();
}
Return connection;
}
}