需要把String類型數據轉換成Reader,然後再使用setCharacterStream插入數據庫中。
例如下例中,要插入StringlongStr,則先轉換成Byte[],再ByteArrayInputStream,最後InputStreamReader。
添加或更新clob型數據,如下所示(以更新爲例):
PreparedStatement pstmt=conn.prepareStatement(“update tablename set column1=? “+條件語句);
byte[] bytes_zyjs = longStr.getBytes();
ByteArrayInputStream baisss = new ByteArrayInputStream(bytes_zyjs);
InputStreamReader bais = new InputStreamReader(baisss);
pstmt.setCharacterStream(1,bais,bytes_zyjs.length);
pstmt.executeUpdate();
但是如上方式寫入漢字就會產生亂碼,於是查看資料得知,上述方法多用於oracle下,而mysql下使用的是setBinaryStream方法,只要傳入位置,inputstream,和長度即可。示例如下:
byte[] cert_dataBytes = cert_data.getBytes();
ByteArrayInputStreambais1 = new ByteArrayInputStream(cert_dataBytes);
byte[]prikey_dataBytes = prikey_data.getBytes();
ByteArrayInputStreambais2 = new ByteArrayInputStream(prikey_dataBytes);
String sql ="insert into cert_data values(?,?,?)";
PreparedStatementpstm = null;
try {
conn.setAutoCommit(false);
pstm= conn.prepareCall(sql);
pstm.setInt(1,cert_sn);
pstm.setBinaryStream(2,bais1,cert_dataBytes.length);//使用二進制讀取,可以直接寫入漢字,否則容易產生亂碼
pstm.setBinaryStream(3,bais2, prikey_dataBytes.length);
pstm.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
pstm.close();
} catch(SQLException e) {
e.printStackTrace();
}finally{
try{
if(pstm!= null)
pstm.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
從數據庫中讀取Blob類型數據後,要轉換成String類型,即轉換成InputStream,再從InputStream轉成byte[],再到String即可。如下:
//把數據庫中blob類型轉換成String類型
public String convertBlobToString(Blobblob){
String result ="";
try {
ByteArrayInputStreammsgContent =(ByteArrayInputStream) blob.getBinaryStream();
byte[]byte_data = new byte[msgContent.available()];
msgContent.read(byte_data,0,byte_data.length);
result= new String(byte_data);
} catch(SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
returnresult;
}