【java】java读取图像文件存入oracle中blob字段源代码

最近因为要做点东西很少写文章了。
尤其是技术类的文章。
在网上看了很多关于Java对blob字段的操作。
自己也尝试着写了个,
自己也修改了部分。
代码写得很乱。

数据库:oracle 10G XE
数据源驱动:jdbc12.jar
文件名:WriteBlob
数据库中建立一个为clobtest的表,内有两个字段,name (varchar2(20)),content(blob)。


package dbdriver;

/**
* 2008-09-28
* @author duduli
* email: lxyzj2000@gmail.com
*/
import java.sql.*;
import java.io.*;
import oracle.sql.*;

public class WriteBlob {

public static void main(String[] args) {
try {
String fName2 = "";
String fileName = "E:\\jianxin.bmp";
//E盘下游个jianxin.bmp的图像文件
File f = new File(fileName);
String fName = f.getName();
int i = fName.lastIndexOf('.');
if (i > 0 && i < fName.length()-1){
fName2 = fName.substring(0,i);
}
System.out.println(fName2);
//获得文件名,出去后缀的文件名。
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:XE", "system", "duduli ");
conn.setAutoCommit(false);
BLOB blob = null;
PreparedStatement pstmt = conn.prepareStatement("insert into blobtest(name,content) values(?,empty_blob())");
pstmt.setString(1, fName2);
pstmt.executeUpdate();
pstmt.close();
pstmt = conn.prepareStatement("select content from blobtest where name= ? for update");
pstmt.setString(1, fName2);
ResultSet rset = pstmt.executeQuery();
if (rset.next()) {
blob = (BLOB) rset.getBlob(1);
}

FileInputStream fin = new FileInputStream(f);
System.out.println("file size = " + fin.available());
pstmt = conn.prepareStatement("update blobtest set content=? where name=?");
OutputStream out = blob.getBinaryOutputStream();
byte[] data = new byte[(int) fin.available()];
fin.read(data);
out.write(data);
fin.close();
out.close();
pstmt.setBlob(1, blob);
pstmt.setString(2, fName2);
pstmt.executeUpdate();
pstmt.close();
conn.commit();
conn.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值