One, get the MySQL connection
This is encapsulated as a method for easy use later.
Public Connection getconnection () throws exception{
String url = "Jdbc:mysql://localhost:3306/dbfortest";
String user = "root";
String password = "root";
Class.forName ("Com.mysql.jdbc.Driver");
Connection conn = drivermanager.getconnection (URL, user, password);
Return conn;
}
Ii. storing data in a database
/**
*
* @param file that needs to be passed into the database
* @throws Exception
*/
public void Save (file file) throws exception{
Connection conn = getconnection ();
String sql = "INSERT into Tb_blob (name,myfile) VALUES (?,?)";
PreparedStatement prest = conn.preparestatement (sql);
String Filename=file.getname ();
Prest.setstring (1, filename);//save by file name
FileInputStream fis = new FileInputStream (file);
Prest.setblob (2, Fis,file.length ());//The second parameter requires a InputStream
Prest.execute (); Perform
}
Take out the data and write the file at the same time.
/**
*
* @param the value of the filename column and is the file name
* @throws Exception
*/
public void GetMp3 (String filename) throws exception{
Connection conn = getconnection ();
String sql = "SELECT * from Tb_blob where name=?";
PreparedStatement prest = conn.preparestatement (sql);
Prest.setstring (1, filename);
ResultSet rs = Prest.executequery ();
while (Rs.next ()) {
Blob bl = Rs.getblob ("myfile");//data is saved in "MyFile", here is the data saved here.
InputStream is = Bl.getbinarystream (); View blobs, which can be taken out in the form of streams.
Bufferedinputstream Buffis = new Bufferedinputstream (IS);
Save to Buffout, in the project directory under FileName file
Bufferedoutputstream buffout = new Bufferedoutputstream (new FileOutputStream (filename));
Byte[] buf= new byte[1024];
int len = buffis.read (buf, 0, 1024);
while (len>0) {
Buffout.write (BUF);
Len=buffis.read (buf, 0, 1024);
}
Buffout.flush ();
Buffout.close ();
Buffis.close ();
}
}
A simple example of MySQL blob access