插入二進制數據sql語句怎么寫?
oracle數據庫喜歡搞特殊,二進制字段數據不能直接插入,需先再該字段插入oracle函數返回的的初始數據,然后在查詢更新該字段。下面以Blob字段類型為例:
1.插入初始數據
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection cn= DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.5:1521:orcl", "qywsbspt", "qywsbspt123999");
cn.setAutoCommit(false);
PreparedStatement pst = cn.prepareStatement("insert into t_uploadfile (file_id,file_content) values (?,EMPTY_BLOB())");
pst.setObject(1,8888);
pst.excuteUpdate();
2.查詢更新該字段
pst = cn.prepareStatement("select file_content from t_uploadfile for updatewhere file_id = ? ");
pst.setObject(1,8888);
ResultSet rs = pst.excuteQuery();
BLOB blob = null ; //不是java.sql.Blob,而是oralce.sql.BLOB
if(rs.next())
blob = (BLOB)rs.getBlob(1); //獲取該字段
OutputStream os =blob.getBinaryOutputStream(); //打開操作該字段的流
InputStream is = ...... //獲取要插入的二進制文件的輸入流
int buffer = -1;
while((buffer = is.read())!=-1){
os.write(buffer);
}
is.close();
os.close();
cn.commit();
rs.close();
pst.close();
cn.close();