将图片存储到数据库中

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);
	}
}

  

posted @ 2019-07-16 19:25  青衫客36  阅读(1201)  评论(0编辑  收藏  举报