JDBC(No.11)

来源:互联网 发布:猫会游泳吗 知乎 编辑:程序博客网 时间:2024/06/04 01:22
  

JDBC的五个步骤:

1、          建立连接,得到Connection对象(利用个用户名、密码和数据库服务器建立连接并且打开指定的数据

2、          利用Connection 对象获取Statement对象

3、          利用Statement对象执行指定的SQL语句

4、          处理结果

如果是查询:那么获取ResultSet对象,进行返回记录的相应操作

5、          善后处理

BLOB

BLOB用来存储大段的二进制数据, 例如图片, 音频, 视频. LONGBLOB最大4G

存储BLOB

PreparedStatement ps = conn.prepareStatement("insert into big_binary(file) values(?)");

File file = new File("src/cn/itcast/jdbc1/clob_blob/IMG_0007.jpg");

InputStream in = new FileInputStream(file);

ps.setBinaryStream(1, in, (int) file.length());

ps.executeUpdate();

读取BLOB

PreparedStatement ps = conn.prepareStatement("select file from big_binary");

ResultSet rs = ps.executeQuery();

if (rs.next()) {

   InputStream in = rs.getBinaryStream(1);

   // 这个InputStream就是从数据库中读取数据的流, 操作这个流来读取数据

}

存储TEXT

PreparedStatement ps = conn.prepareStatement("insert into clob(file) values(?)");

File file = new File("src/cn/itcast/jdbc1/clob_blob/ClobDemo.java");

Reader reader = new FileReader(file);

ps.setCharacterStream(1, reader, (int) file.length());

ps.executeUpdate()

也可以使用ps.setString()直接设置, 但如果字符串太大, 有可能超出虚拟机内存

读取TEXT

PreparedStatement ps = conn.prepareStatement("select file from clob");

ResultSet rs = ps.executeQuery();

if (rs.next()) {

Reader reader = rs.getCharacterStream(int columnIndex);

// 这个Reader就是从数据库中读取数据的流, 操作这个流来读取数据

}

也可以使用rs.getString(), 在字符串太大的情况下, 同样有可能超出虚拟机内存

原创粉丝点击