JDBC中关于二进制大对象的处理
在我们的工作中,我们可能会遇到一些比如关于图片等二进制对象的处理。那么我们应该如何来处理这些图片呢。当然JDBC中也提供了相关的方法来操作这些二进制的对象。但是在实际的开发当中,我们很可能不会使用数据库来存这样的一些图片信息。我们可能会在服务端来进行处理。我们也可能会是从客户端中接收到一个流对象。然后我们就可以在服务端来进行处理。但是就像在处理大文件的时候,其实这时候涉及的也是流的一些操作而已。并没有什么的特别之处。
我们来看一个实际的例子:
package com.bjsxt.jdbc;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 测试BLOB 二进制大对象的使用
* @author 高淇 www.sxt.cn
*
*/
public class Demo10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
OutputStream os = null;
try {
//加载驱动类
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","123456");
// ps = conn.prepareStatement("insert into t_user (username,headImg) values (?,?) ");
// ps.setString(1, "高淇");
// ps.setBlob(2, new FileInputStream("d:/icon.jpg"));
// ps.execute();
ps = conn.prepareStatement("select * from t_user where id=?");
ps.setObject(1, 101026);
rs = ps.executeQuery();
while(rs.next()){
Blob b = rs.getBlob("headImg");
is = b.getBinaryStream();
os = new FileOutputStream("d:/a.jpg");
int temp = 0;
while((temp=is.read())!=-1){
os.write(temp);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(is!=null){
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(os!=null){
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if(ps!=null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}