jdbc操作oracle Blob字段读写

写入Oracle Blob字段

/**
* 插入Blob字段
*/
public static void insertBlobField(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
String url = "jdbc:oracle:thin:@192.168.8.100:1521:ORCL";
String username = "shouyao";
String password = "shouyao";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
stmt = conn.createStatement();
stmt.execute("insert into a_blob_test(id,picture) values(1,empty_blob())");
rs = stmt.executeQuery("select t.id,t.picture from a_blob_test t where t.id = 1 for update");
File f1 = new File("E:\\hel\\MyEclipse 10.0\\druggist\\code\\src\\test\\test.jpg");
FileInputStream fis = new FileInputStream(f1);
OutputStream os = null;
if(rs.next()){
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(2);
os = blob.getBinaryOutputStream();
byte[] b = new byte[(int) f1.length()];
fis.read(b);
os.write(b);
os.flush();
}
os.close();
conn.commit();
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}



读取oracle Blob字段

/**
* 查询Blob字段存储的图片文件,并输出
*/
public static void queryBlobField(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:oracle:thin:@192.168.8.100:1521:ORCL";
String username = "shouyao";
String password = "shouyao";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
rs = stmt.executeQuery("select t.id,t.picture from a_blob_test t where t.id = 1");
//文件保存的路径
File f1 = new File("E:\\hel\\MyEclipse 10.0\\druggist\\code\\src\\test\\test1.jpg");
FileOutputStream fos = new FileOutputStream(f1);
InputStream is = null;
if(rs.next()){
Blob blob = rs.getBlob(2);
is = blob.getBinaryStream();
int len =0;
byte[] b = new byte[1024];
while((len = is.read(b)) != -1){
fos.write(b,0,len);
}
}
fos.close();
is.close();
rs.close();
stmt.close();
conn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值