Oracle的Blob字段比較特殊
寫入Blob字段和寫入其它類型字段的方式非常不同
這需要你先插入一個empty的blob
看下面的JDBC的demo
import java
import java
import oracle
public class WriteBlob {
public static void main(String[] args) {
try {
DriverManager
Connection conn = DriverManager
conn
BLOB blob = null;
PreparedStatement pstmt = conn
pstmt
pstmt
pstmt
pstmt = conn
pstmt
ResultSet rset = pstmt
if (rset
String fileName =
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
System
pstmt = conn
OutputStream out = blob
int count =
byte[] data = new byte[(int)fin
fin
out
/*
byte[] data = new byte[blob
while ((count = fin
total += count;
out
}
*/
fin
out
pstmt
pstmt
pstmt
pstmt
mit();
conn
} catch (SQLException e) {
System
e
} catch (IOException e) {
System
}
}
}
仔細看上例
into javatest(name
select content from javatest where name= ? for update;
注意!!!必須加for update
用cursor往數據庫寫數據
這裡面還有一點要提醒大家
JDK
另外要注意的是
java
oracle
注意看blob的大小寫
下面看看用Hibernate怎麼寫
這是Cat對象定義
package com
import java
public class Cat {
private String id;
private String name;
private char sex;
private float weight;
private Blob image;
public Cat() { }
public String getId() { return id; }
public void setId(String id) { this
public String getName() { return name; }
public void setName(String name) { this
public char getSex() { return sex; }
public void setSex(char sex) { this
public float getWeight() { return weight; }
public void setWeight(float weight) { this
public Blob getImage() { return image; }
public void setImage(Blob image) { this
}
這是Cat
<?xml version=
<!DOCTYPE hibernate
<hibernate
<class name=
<!
<id name=
<generator class=
</id>
<property name=
<property name=
<property name=
<property name=
</class>
</hibernate
下面是完整的用Hibernate寫入Blob的例子
package com
import java
import net
import oracle
import java
public class TestCatHibernate {
public static void testBlob() {
Session s = null;
byte[] buffer = new byte[
buffer[
try {
SessionFactory sf = HibernateSessionFactory
s = sf
Transaction tx = s
Cat c = new Cat();
c
c
s
s
s
BLOB blob = (BLOB) c
OutputStream out = blob
String fileName =
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
int count =
byte[] data = new byte[(int)fin
fin
out
fin
out
s
mit();
} catch (Exception e) {
System
} finally {
if (s != null)
try {
s
} catch (Exception e) {}
}
}
}
From:http://tw.wingwit.com/Article/program/Oracle/201311/17139.html