将图片存储到数据库中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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 @   青衫客36  阅读(1201)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示