標籤:java程式 資料庫表 sequence blob
在寫java程式過程中,如何讀取Oracle資料庫表某類型為blob的欄位?
以下是我在寫程式的時候一種解決方案。核心語句。(傳上來做了修改,格式不要學習,養成良好習慣)
詳細請參考:
讀取序列ID:http://blog.csdn.net/yzsind/article/details/6918506
BLOB相關:http://jslfl.iteye.com/blog/1771949
http://www.linuxidc.com/Linux/2011-08/40218.htm
http://xwwccsucn.blog.163.com/blog/static/979145792011925234392/
1. 讀取BLOB欄位
import oracle.sql.BLOB;
ResultSet rs = ps.executeQuery(sql);
BLOB blob = (BLOB) rs.getBlob("content");
String s = blobToString(blob);
2. blobToString()方法
private String blobToString(BLOB blob) throws SQLException, UnsupportedEncodingException {
long BlobLength; // BLOB欄位長度
int i = 1; // 迴圈變數
byte[] bytes; // BLOB臨時儲存位元組數組
String newStr = ""; // 返回字串
byte[] msgContent = blob.getBytes(); // BLOB轉換為位元組數組
BlobLength = blob.length(); //擷取BLOB長度
if (msgContent == null || BlobLength == 0) //如果為空白,返回空值
{
return "";
} else {
while (i <= BlobLength) //迴圈處理字串轉換,每次1024;Oracle字串限制最大4k
{
bytes = blob.getBytes(i, 1024);
i = i + 1024;
newStr = newStr + new String(bytes);
}
}
return newStr;
}
3. update BLOB欄位
public void insertData(String task_name, String tast_target) {
int num = 0;
String hql = "insert into table values(sequence_id.nextval,?,EMPTY_BLOB()) returning id into ?";
try {
Connection conn = GlobalData.getConnection();
OraclePreparedStatement ops = (OraclePreparedStatement) conn.prepareStatement(hql);
ops.setString(1, task_name);
ops.registerReturnParameter(2, OracleTypes.NUMBER);
num = ops.executeUpdate();
ResultSet rset = ops.getReturnResultSet(); // rest is not null
long id = 0;
while (rset.next()) {
id = rset.getLong(1);
System.out.println("Insert returnning: " + id);
}
//更新blob欄位
Statement bst = conn.createStatement();
ResultSet bset = bst.executeQuery("select tast_target from table where id=" + id + " FOR UPDATE");
BLOB blob = null;
while (bset.next()) {
blob = ((OracleResultSet) bset).getBLOB(1);
}
final java.io.BufferedOutputStream out = new java.io.BufferedOutputStream(blob.getBinaryOutputStream());//輸出資料流
ByteArrayInputStream streamTemp = null;//輸入資料流
try {
streamTemp = new ByteArrayInputStream(tast_target.getBytes("ISO-8859-1"));
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(OracleGenelDaoImpl.class
.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = new byte[1024];//緩衝區
int length = -1;
try {
while ((length = streamTemp.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
streamTemp.close();
out.close();
} catch (IOException ex) {
Logger.getLogger(OracleGenelDaoImpl.class
.getName()).log(Level.SEVERE, null, ex);
}
conn.commit();
ops.close();
bst.close();
} catch (SQLException ex) {
Logger.getLogger(OracleGenelDaoImpl.class
.getName()).log(Level.SEVERE, null, ex);
}
}
本文出自 “我會努力” 部落格,請務必保留此出處http://meijia.blog.51cto.com/8684191/1563867
Java讀取/更新Oracle資料庫blob欄位