JDBC之CLOB与BLOB
2016-07-22 23:01
337 查看
今天我们来介绍一下CLOB与BLOB的存储与读取。那么CLOB和BLOB是什么呢?
CLOB:大字符数据,例如长篇小说
BLOB:二进制数据,例如图片、视频
首先我们定义一个新表:
下面我们将分别对长文本和图片进行读取和存储。根据面向对象的思想,我们建立Lob类:
下面我们将小说和图片写入到数据库,二话不说直接上代码:
这里都是以流的形式进行的存储。那么我们如何将这些数据从数据库中读取出来呢?
这就是我们本章要讲的内容。后面会有更精彩的内容等着你们!
CLOB:大字符数据,例如长篇小说
BLOB:二进制数据,例如图片、视频
首先我们定义一个新表:
create table `t_lob` ( `id` int (11), `context` text , `pic` blob );
下面我们将分别对长文本和图片进行读取和存储。根据面向对象的思想,我们建立Lob类:
public class Lob { private File context; private File pic; //构造方法,get和set方法省略 }
下面我们将小说和图片写入到数据库,二话不说直接上代码:
private static int addContext(Lob lob) throws Exception { Connection con = dbUtil.getCon(); String sql = "insert into t_lob values(null,?,?)"; PreparedStatement pstmt = con.prepareStatement(sql); // 存小说 File context = lob.getContext(); InputStream inputStream = new FileInputStream(context); pstmt.setAsciiStream(1, inputStream, context.length()); // 存图片 File pic = lob.getPic(); InputStream inputStream2 = new FileInputStream(pic); pstmt.setBinaryStream(2, inputStream2, pic.length()); int result = pstmt.executeUpdate(); dbUtil.close(pstmt, con); return result; }
这里都是以流的形式进行的存储。那么我们如何将这些数据从数据库中读取出来呢?
public static void getContext(int id) throws Exception { Connection con = dbUtil.getCon(); String sql = "select * from t_lob where id=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { //读小说 Clob clob = rs.getClob("context"); String context = clob.getSubString(1, (int) clob.length()); System.out.println(context); //读图片 Blob blob = rs.getBlob("pic"); FileOutputStream out = new FileOutputStream(new File("E:/pic.jpg")); out.write(blob.getBytes(1, (int) blob.length())); out.close(); } rs.close(); dbUtil.close(pstmt, con); }
这就是我们本章要讲的内容。后面会有更精彩的内容等着你们!
相关文章推荐
- jdbc中的Statement和PreparedStatement接口对象
- JDBC 数据库常用连接 链接字符串
- JDBC连接Access数据库的几种方式介绍
- 基于JDBC封装的BaseDao(实例代码)
- JDBC程序更新数据库中记录的方法
- jdbc链接远程数据库进行修改url操作
- JDBC 程序的常见错误及调试方法
- 在Java的JDBC使用中设置事务回滚的保存点的方法
- Java中使用JDBC操作数据库简单实例
- Java加载JDBC驱动程序实例详解
- JSP使用JDBC完成动态验证及采用MVC完成数据查询的方法
- JSP基于JDBC的数据库连接类实例
- JSP中使用JDBC访问SQL Server 2008数据库示例
- jsp+jdbc实现连接数据库的方法
- 解析jdbc处理oracle的clob字段的详解
- JDBC数据库的使用操作总结
- jdbc操作mysql数据库实例
- JSP使用JDBC连接MYSQL数据库的方法
- Java开发Oracle数据库连接JDBC Thin Driver 的三种方法
- java使用jdbc操作数据库示例分享