Jdbc扩展---Jdbc处理二进制数据
一 使用目的
一般是向数据库库中插入图片和从数据库中读取图片
二 代码介绍
1.向数据库中插入图片
public void insert() {
Connection con = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
// 获取连接
con = DBManager.getConnection();
// 定义sql语句
String sql = "insert into testblob (image) value(?)";
// 创建预处理对象
st = con.prepareStatement(sql);
// 为占位符赋值
File f = new File("1.jpg");
st.setBinaryStream(1, new FileInputStream(f), f.length());
// 执行更新语句
int result = st.executeUpdate();
// 判断
if (result > 0) {
System.out.println("插入成功");
} else {
System.out.println("插入失败");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
DBManager.release(con, st, rs);
}
}
注:想数据库中输入图片最重要的是:
File f = new File("1.jpg");
st.setBinaryStream(1, new FileInputStream(f), f.length());
2.从数据库中读取图片
public void find() {
Connection con = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
// 获取连接
con = DBManager.getConnection();
// 定义sql语句
String sql = "select image from testblob where id=1";
// 创建预处理对象
st = con.prepareStatement(sql);
// 执行更新
rs = st.executeQuery();
// 判断
if (rs.next()) {
// 读取
InputStream fis = rs.getBinaryStream("image");
// 定义缓冲区,读取到缓冲区 中
byte[] buff = new byte[1024];
int len = 0;
FileOutputStream fos = new FileOutputStream("3.jpg");
while ((len = fis.read(buff)) > 0) {
fos.write(buff, 0, len);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBManager.release(con, st, rs);
}
}
注:最重要的部分:
if (rs.next()) {
// 读取
InputStream fis = rs.getBinaryStream("image");
// 定义缓冲区,读取到缓冲区 中
byte[] buff = new byte[1024];
int len = 0;
FileOutputStream fos = new FileOutputStream("3.jpg");
while ((len = fis.read(buff)) > 0) {
fos.write(buff, 0, len);
}
}
注:配置文件在上一篇有附加