java oracle数据blob的操作
发布网友
发布时间:2022-04-08 20:21
我来回答
共1个回答
热心网友
时间:2022-04-08 21:51
// 下面为一个完整的例子,如果用framework,需要做一定修改
写入
public boolean saveWordFile(String filePath) {
File file = new
File(filePath);
Connection conn = getConnection();
try
{
java.sql.Statement st = conn.createStatement();
conn.setAutoCommit(false);
st.execute("insert into table_name
values(1,empty_blob())");
ResultSet rs =
st
.executeQuery("select id,word from table_name where
id=1 for update");
if (rs.next()) {
BLOB blob
= (BLOB) rs.getBlob("word");
OutputStream outStream =
blob.getBinaryOutputStream();
InputStream fin = new
FileInputStream(file);
byte[] b = new
byte[blob.getBufferSize()];
int len = 0;
while ((len = fin.read(b)) != -1) {
outStream.write(b, 0,
len);
}
fin.close();
outStream.flush();
outStream.close();
conn.commit();
conn.close();
}
}
catch (SQLException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
} catch
(FileNotFoundException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
读取
public void getWordFile(String id) {
Connection conn =
getConnection();
java.sql.Statement st;
try
{
st = conn.createStatement();
ResultSet rs =
st.executeQuery("select id,word from table_name where
id='"+id+"'");
if (rs.next()) {
BLOB blob =
(BLOB) rs.getBlob("word");
File file = new
File("c://filename.doc");
FileOutputStream output = new
FileOutputStream(file);
InputStream input =
blob.getBinaryStream();
byte[] buffer = new
byte[1024];
int i = 0;
while ((i =
input.read(buffer)) != -1) {
output.write(buffer, 0,
i);
}
}
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
修改
public void updateblob(String id){
Connection
conn=getConnection();
Statement stem=null;
ResultSet rs=null;
try{
conn.setAutoCommit(false);
stem=conn.createStatement();
rs = stem.executeQuery("select word
from table_name where id='"+id+"' for update");
if
(rs.next()) {
BLOB blob = (BLOB) rs.getBlob("word");
OutputStream outStream = blob.getBinaryOutputStream();
InputStream fin = new FileInputStream("c://2.doc");
byte[] b = new byte[blob.getBufferSize()];
int
len = 0;
while ((len = fin.read(b)) != -1) {
outStream.write(b, 0, len);
}
fin.close();
outStream.flush();
outStream.close();
conn.commit();
conn.close();
}
} catch (Exception ex){
try {
conn.rollback();
} catch (SQLException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
System.out.println(ex.getMessage());
}
}
追问我的是直接表里面读出来又放到另一个表中blob类型的,能直接放吗
追答只能这样处理blob/clob的