码迷,mamicode.com
首页 > 数据库 > 详细

JDBC学习笔记(9):访问二进制数据

时间:2015-03-19 20:05:41      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

数据库准备:

create table blob_test
(
    id integer not null auto_increment,
    big_bit blob not null,
    primary key(id)
);

在工程目录下新建一个images文件夹,存入一张zhukov.jpg图片

技术分享

向数据库插入二进制数据:

 1 public static void create() throws SQLException, IOException {
 2         Connection conn = null;
 3         PreparedStatement ps = null;
 4         ResultSet rs = null;
 5         try {
 6             conn = JdbcUtils.getConnection();
 7             
 8             String sql = "insert into blob_test(big_bit) values(?)";
 9             ps = conn.prepareStatement(sql);
10             File file = new File("src/images/zhukov.jpg");
11             InputStream in = new BufferedInputStream(new FileInputStream(file));
12             ps.setBinaryStream(1, in, (int)file.length());
13             int i = ps.executeUpdate();
14             in.close();
15             System.out.println("i~~~~~" + i);
16         } finally {
17             JdbcUtils.close(rs, ps, conn);
18         }
19                 
20     }
【运行结果】:
i~~~~~1 
查看数据库,发现仅显示如下图,blob类型有大小限制
技术分享
 
从数据库中读取二进制数据:
public static void read() throws IOException, SQLException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            stmt = conn.createStatement();
            String sql = "select big_bit from blob_test";
            rs = stmt.executeQuery(sql);
            while(rs.next()) {
                InputStream in = rs.getBinaryStream(1);
                
                File file = new File("src/images/zhukov_bak.png");
                OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
                byte[] buffer = new byte[1024];
                for (int i = 0; (i=in.read(buffer))>0; ) {
                    out.write(buffer, 0, i);
                }
                out.close();
                in.close();
            }
        } finally {
            JdbcUtils.close(rs, stmt, conn);
        }
    }

刷新工程,将在images目录下增加了zhukov_bak.png

JDBC学习笔记(9):访问二进制数据

标签:

原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4351344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!