插入
package com.study.jdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBC_blob_insert {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
FileInputStream in = null;
try {
conn = DBUtil.getConnection();
String sql = "insert into t_img(name,img) values (?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1,"测试图片");
in = new FileInputStream("F:\\Administrator\\Pictures\\1.jpg");
ps.setBlob(2, in);
int count = ps.executeUpdate();
System.out.println("插入" + count +"条数据");
} catch (SQLException | FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if(in != null){
try{
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
DBUtil.close(conn,ps,null);
}
}
}
查询
package com.study.jdbc;
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBC_blob_query {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
String sql = "select img from t_img where name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,"测试图片");
rs = ps.executeQuery();
while (rs.next()){
InputStream in = rs.getBinaryStream("img");// 通过结果集列名 获取内容 赋值给输入流
OutputStream out = new FileOutputStream("E:/读取文件.jpg"); // 定义一个输出流将 内容输出到电脑指定位置
byte[] bytes = new byte[1024]; // 定义字节大小
int readCount = 0; // 读取内容初始值
while((readCount = in.read(bytes)) != -1){ // 当读取的内容 不为空时
out.write(bytes,0,readCount); // 将读取的内容写入输出流
}
out.flush(); // 刷新输出流
in.close(); // 关闭输入流
out.close(); // 关闭输出流
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
DBUtil.close(conn,ps,rs);
}
}
}