Oracle10g BLOB数据插入问题浅议

本文介绍如何在Oracle数据库中使用empty_blob()函数存储图片数据。通过示例代码详细讲解了创建包含BLOB类型的表、插入空BLOB记录及更新图片数据的具体步骤。

在Oracle中大数据类型一般常用oracle.sql.BLOB来表示,不同于mysql中的通用的java.sql.Blob接口,因此在插入图片数据到oracle的时候不能直接插入图片,一般采用oracle的empty_blob()函数,先生成空的BLOB对象插入到表中,然后再读取该记录,重新update图片数据到相应字段中;

举例如下:

创建表sql语句
drop sequence seq_changedata_infoid;
create sequence seq_changedata_infoid increment by 1 start with 1;
CREATE TABLE changedata_info (
id number(20) NOT NULL ,
version_id varchar2(20) not null,
sql_id number(20) default NULL,
sql_content varchar2(256) default NULL,
photo blob,
PRIMARY KEY (id)
);

直接sql插入语句为:

insert into changedata_info(id,version_id,sql_id,sql_content,photo)values(1,'1200',1,'update ....',empty_blob())

程序代码如下:

public static void main(String[] args){


BLOB blob = null; //图片类型
OutputStream outputStream = null; //输出流
File file = null; //文件
InputStream inputStream = null; //输入流

ResultSet rs = null;
Statement sm = null;
Statement smt = null;
ResultSet rr = null;

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager
.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"system", "admin");

con.setAutoCommit(false); //事物由程序员操作
String sql = "";



//DesEncrypt tm = new DesEncrypt();
//tm.getKey("aabb");
//String strDes = "";
//String str ="";

for(int i =8;i<11;i++){

int id ;
id = 1000 + i;
String version_id = "20080813060839";

int sql_id = i;

String sql_content = "update ticketinfo set name = mingtian where id = 50006";

String sqlInsert = "insert into changedata_info(id,version_id,sql_id,sql_content,photo)values("
+ id
+","
+ version_id
+ ","
+ sql_id
+ ",'"
+ sql_content
+ "',"
+ "empty_blob()"
+ ")";

//con.setAutoCommit(false); //事物由程序员操作
smt = con.createStatement();

//rs = sm.executeQuery(sqlInsert);//插入数据 ---当前图片为空
smt.execute(sqlInsert);

String sqlUpdate = "select photo from changedata_info where id='" + id + "'";

sm = con.createStatement();
ResultSet r= sm.executeQuery(sqlUpdate + " for update");
if (r.next()) {
blob = (BLOB) r.getBlob(1);
byte [] photo = r.getBytes("photo");
outputStream = blob.getBinaryOutputStream();
file = new File("c:\\11\\photo.jpg");//c:\\11\\photo.jpg
inputStream = new FileInputStream(file);
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ((len = inputStream.read(b)) != -1) {
System.out.println(len);
outputStream.write(b, 0, len);
}
}



}
con.commit();
con.close();




} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

此代码经过测试,与mysql的图片插入做过比较之后有所感悟,所以唠叨一下....;-)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值