packageblobtest;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.sql.Blob;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;public classReadWriteBlobwithMysql
{privateConnection con;privateStatement stmt;publicStatement getStmt()
{returnstmt;
}public voidsetStmt(Statement stmt)
{this.stmt =stmt;
}publicResultSet getRs()
{returnrs;
}public voidsetRs(ResultSet rs)
{this.rs =rs;
}
ResultSet rs;publicConnection getCon()
{returncon;
}public voidsetCon(Connection con)
{this.con =con;
}public void insert(Connection con) throwsSQLException
{
String fileName= "E:\\JavaProject\\HelloWorld\\src\\blobtest\\test.html";
File file= newFile(fileName);try{
FileInputStream fis= newFileInputStream(file);
String sql= "insert into blobtest values(‘12‘,‘0000‘,‘平安银行‘,?)";
PreparedStatement prest=con.prepareStatement(sql);
prest.setBlob(1, fis, file.length());
prest.execute();
}catch(FileNotFoundException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}
}public void queryBlob(String id, Connection con) throwsIOException
{
String fileName= "E:\\JavaProject\\HelloWorld\\src\\blobtest\\test1.html";
String sql= "select * from blobtest where primary_id= ?";try{
PreparedStatement prest=con.prepareStatement(sql);
prest.setString(1, id);
ResultSet rs=prest.executeQuery();while(rs.next())
{
Blob bl= rs.getBlob("blob_data");//数据保存在表的blob_data字段中,这里取出这里保存的数据。
InputStream is = bl.getBinaryStream(); //查看blob,可以通过流的形式取出来。 注意一定要是用流的方式读取出来
BufferedInputStream buffis = newBufferedInputStream(is);//保存到buffout
BufferedOutputStream buffout = new BufferedOutputStream(newFileOutputStream(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();
}
}catch(SQLException e)
{//TODO Auto-generated catch block
e.printStackTrace();
}
}publicReadWriteBlobwithMysql(Connection con)
{this.setCon(con);try{
stmt=con.createStatement();
}catch(SQLException e)
{
e.printStackTrace();
}
}public static voidmain(String[] args)
{
Connection con=JDBCUtil.getConnection();
ReadWriteBlobwithMysql dao= newReadWriteBlobwithMysql(con);try{//dao.createTable();//dao.insert(con);
dao.queryBlob("12",con);
}catch(IOException e)
{
e.printStackTrace();
}finally{
JDBCUtil.close(dao.getRs(), dao.getStmt(), dao.getCon());
}
}
}