java String与Blob类型数据转换
需要把String类型数据转换成Reader,然后再使用setCharacterStream插入数据库中。
例如下例中,要插入String longStr,则先转换成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();
byte[] cert_dataBytes = cert_data.getBytes(); ByteArrayInputStream bais1 = new ByteArrayInputStream(cert_dataBytes); byte[] prikey_dataBytes = prikey_data.getBytes(); ByteArrayInputStream bais2 = new ByteArrayInputStream(prikey_dataBytes); String sql = "insert into cert_data values(?,?,?)"; PreparedStatement pstm = 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类型 public String convertBlobToString(Blob blob){ String result = ""; try { ByteArrayInputStream msgContent =(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(); } return result; }