blob和clob都是用来处理大字段的
其中blob适用于非文本数据,图片、视频、pdf文件、MP3文件等等,BLOB是二进制大对象,按字节存储。
clob适用于处理大文本数据,CLOB是字符型大对象,按字符进行存储。
package com.Aes;
import java.io.*;
import java.sql.*;
public class BlobTest {
//url
private static String url = "jdbc:oracle:thin:@数据库服务器IP地址/数据库实例名";
//user
private static String user = "用户名";
//password
private static String password = "密码";
//驱动程序类
private static String driverClass = "oracle.jdbc.driver.OracleDriver";
public static void main(String[] args) {
write();
//read();
}
//从数据库读取一条记录并抽取第四列的BLOB对象
private static void read() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = BlobTest.getConnection();
String sql = "select * from TAB_COMPANY_PROMISE where id=?";
stmt = conn.prepareStatement(sql);
//加入sql语句的参数
stmt.setString(1,"7556AF3FD2F8499EBCFE1B78549C8530");
rs = stmt.executeQuery();
//获取查询结果
if(rs.next()){
//我的查询结果的第四列是BLOB对象
Blob blob = rs.getBlob(4);
//根据自定义的文件名在本地创建空文件,本地创建的文件后缀要与事先
//保存的文件吻合
File f = new File("d:"+File.separator+"testblob.pdf");
OutputStream out = null;
//初始化字节流
out = new FileOutputStream(f);
//以字节流的形式将BLOB对象写入创建的文件 "f"
out.write(blob.getBytes(1, (int)blob.length()));
out.close();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs != null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if(conn != null) {
conn.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
private static void write() {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = BlobTest.getConnection();
String sql = "UPDATE TAB_COMPANY_PROMISE SET PROMISEFILE=? WHERE ID = '7556AF3FD2F8499EBCFE1B78549C8530'";
stmt = conn.prepareStatement(sql);
//根据需要上传的文件路径初始化File类对象
File f = new File("d:"+File.separator+"test.pdf");
InputStream in = null;
//获取文件流对象
in = new FileInputStream(f);
//将文件读为二进制流,并写到第一个参数中
stmt.setBinaryStream(1,in,(int)f.length());
// 执行插入/更新数据库操作
stmt.executeUpdate();
System.out.println("添加成功!");
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try{
if(stmt != null){
stmt.close();
}
if(conn != null) {
conn.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
/**
* 获取数据库连接
*/
public static Connection getConnection(){
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return null;
}
}
上面贴的代码算伪代码了吧,可以自行修改,但是处理逻辑是没问题的。
数据库中BLOB字段保存形式如下:
总的来说操作并不太复杂,其中涉及的主要知识点是jdbc相关操作BLOB数据的方法,以及文件流操作;比起base64少了加密操作,但个人感觉BASE64更方便。
BLOB:字节流操作。
CLOB:字符流操作。