package blob;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.junit.Test;
import pers.mjn.util.JdbcUtil;
public class BlobTest {
// 把c盤的outman.png圖片的數據保存到t_image表中
@Test
public void test1() throws Exception {
String sql = "INSERT INTO t_image (img) VALUES (?)";
Connection conn = JdbcUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setBlob(1, new FileInputStream("C:/1.png"));
ps.executeUpdate();
JdbcUtil.close(conn, ps, null);
}
// t_image表中的圖片數據保存到磁盤中
@Test
public void test2() throws Exception {
String sql = "SELECT * FROM t_image WHERE id = ?";
Connection conn = JdbcUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setLong(1, 1L);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
Blob blob = rs.getBlob("img");
InputStream in = blob.getBinaryStream();
// 文件拷貝操作
Files.copy(in, Paths.get("D:/2.png"));
}
JdbcUtil.close(conn, ps, rs);
}
}