1. The database table structure is as follows
The data type here is selected based on the size of the inserted data.
1. The implementation of the following, mainly the picture into a binary database
1Connection conn=NULL;2PreparedStatement st=NULL;3String sql= "INSERT into users (USERNAME,PASSWORD,REGDATE,IMG) VALUES (?,?,?,?)";4 Try {5 if(conn==NULL){6conn =db.getconnection ();7 }8St =conn.preparestatement (SQL);9File file=NewFile ( This. GetClass (). getClassLoader (). GetResource (".. /.. /"). GetPath () +" 1.jpeg ");TenInputStream input=NewBufferedinputstream (Newfileinputstream (file)); OneSt.setstring (1, User.getusername ()); ASt.setstring (2, User.getpassword ()); -St.setdate (3,NewDate (User.getregdate (). GetTime ())); -St.setbinarystream (4, Input, (int) file.length ()); It is important to Note that the following file.length () data type is long, where it needs to be strongly converted to int type the intresult=st.executeupdate (); - if(result>0){ - return true; - } +}Catch(SQLException e) { - e.printstacktrace (); +}Catch(FileNotFoundException e) { A e.printstacktrace (); at}finally{ - if(st!=NULL) - Db.close (ST); - if(conn!=NULL) - Db.close (conn); - } in return false;
3. Note:
Setbinarystream (int index,inputstream input,long) in the PreparedStatement object The method exists in jdk1.6, but is not implemented in MySQL JDBC, and the following error is reported if the file length is not converted to int
Java.lang.AbstractMethodError:com.mysql.jdbc.PreparedStatement.setBinaryStream (Iljava/io/inputstream; J) V
4. Remove binary files from the database
1Connection conn =NULL;2PreparedStatement st =NULL;3String sql = "SELECT * from Users where id=?";4 Try {5 if(conn = =NULL) {6conn =jdbcutil.getconnection ();7 }8St =conn.preparestatement (SQL);9St.setint (1, User.getid ());TenFile File =NewFile ( This. GetClass (). getClassLoader (). GetResource (".. /.. /"). GetPath () +" Back.jpeg "); OneOutputStream output =NewBufferedoutputstream (Newfileoutputstream (file)); AResultSet result =st.executequery (); - while(Result.next ()) { - byte[] by =New byte[1024]; the inti = 0; -InputStream input = Result.getbinarystream (5); //Remove binary data - Try { - while((i = Input.read (by))! =-1) +Output.write (by, 0, i); //write to file via output stream -}Catch(IOException e) { + e.printstacktrace (); A } at - } - -}Catch(SQLException e) { - e.printstacktrace (); -}Catch(FileNotFoundException e) { in e.printstacktrace (); -}finally { to if(St! =NULL) + Jdbcutil.close (ST); - if(Conn! =NULL) the Jdbcutil.close (conn); * } $ return false;
Java operation MySQL operation large object