blob和clob都是用來處理大字段的
其中blob適用於文件類型的數據諸如:圖片、word文件、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 = JdbcUtil.getConnection();
String sql = "select * from TAB_COMPANY_PROMISE where id=?";
stmt = conn.prepareStatement(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);
//將對應的內容寫入磁盤空間對應目錄的對應文件裏
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 = JdbcUtil.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);
}
}
}
數據庫中BLOB字段保存形式如下:
總的來說操作並不太複雜,其中涉及的主要知識點是jdbc相關類的方法,以及文件流操作;比起base64少了加密操作,但個人感覺BASE64更方便。