create table blob_text(
id integer primary key auto_increment,
big_bit blob
)charset utf8;
对二进制文件的操作与对文本文件的操作大致相同,只是将字符输入输出流改为字节输入输出流.
public class BlobText {
public static void main(String[] args) throws SQLException, IOException {
creat();
read();
}
static public void creat() throws SQLException, IOException{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//建立连接
con = JDBCUtils.getConnection();
//创建语句
String sql = "insert into blob_text(big_bit) values(?)";
ps = con.prepareStatement(sql);
//读取文件
File file = new File("src/imag.jpg");
//将文件转换为字节流并读取
InputStream in = new BufferedInputStream(new FileInputStream(file));
ps.setBinaryStream(1,in,(int)file.length());
//执行语句
int i = ps.executeUpdate();
System.out.println("i:"+i);
}finally{
JDBCUtils.free(rs, ps, con);
}
}
static void read() throws SQLException, IOException{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//建立连接
con = JDBCUtils.getConnection();
//创建语句
String sql = "select big_bit from blob_text";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
//将数据库内容存储到imag_2.jpg
File file = new File("src/imag_2.jpg");
// 1 为当前行中指定的列
Blob blob = rs.getBlob(1);
//读出流获取blob的内容
InputStream in = blob.getBinaryStream();
/*
* 也可以直接写成:
* in = rs.getCharacterStream(1);
* 1 为当前行中指定的列
*/
//写入流
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
byte[] buff = new byte[1024];
//将blob内容写入buff字节串中然后将buff写入文件中
for(int i =0;(i=in.read(buff))>0;){
out.write(buff,0,i);
}
out.close();
in.close();
}
}finally{
JDBCUtils.free(rs, ps, con);
}
}
}