Java String与Blob类型数据转换


需要把String类型数据转换成Reader,然后再使用setCharacterStream插入数据库中。

例如下例中,要插入String longStr,则先转换成Byte[],再ByteArrayInputStream,最后InputStreamReader。

添加或更新clob型数据,如下所示(以更新为例):

  1. PreparedStatement pstmt=conn.prepareStatement(“update tablename set column1=? “+条件语句);
  2. byte[] bytes_zyjs = longStr.getBytes();
  3. ByteArrayInputStream baisss = new ByteArrayInputStream(bytes_zyjs);
  4. InputStreamReader bais = new InputStreamReader(baisss);
  5. pstmt.setCharacterStream(1,bais,bytes_zyjs.length);
  6. pstmt.executeUpdate();

但是如上方式写入汉字就会产生乱码,于是查看资料得知,上述方法多用于Oracle下,而mysql下使用的是setBinaryStream方法,只要传入位置,inputstream,和长度即可。示例如下:

  1. byte[] cert_dataBytes = cert_data.getBytes();
  2. ByteArrayInputStream bais1 = new ByteArrayInputStream(cert_dataBytes);
  3. byte[] prikey_dataBytes = prikey_data.getBytes();
  4. ByteArrayInputStream bais2 = new ByteArrayInputStream(prikey_dataBytes);
  5. String sql = "insert into cert_data values(?,?,?)";
  6. PreparedStatement pstm = null;
  7. try {
  8. conn.setAutoCommit(false);
  9. pstm = conn.prepareCall(sql);
  10. pstm.setInt(1,cert_sn);
  11. pstm.setBinaryStream(2, bais1,cert_dataBytes.length);//使用二进制读取,可以直接写入汉字,否则容易产生乱码
  12. pstm.setBinaryStream(3, bais2, prikey_dataBytes.length);
  13. pstm.executeUpdate();
  14. conn.commit();
  15. conn.setAutoCommit(true);
  16. pstm.close();
  17. } catch (SQLException e) {
  18. e.printStackTrace();
  19. }finally{
  20. try {
  21. if(pstm != null)
  22. pstm.close();
  23. } catch (SQLException e) {
  24. e.printStackTrace();
  25. }
  26. }

从数据库中读取Blob类型数据后,要转换成String类型,即转换成InputStream,再从InputStream转成byte[],再到String即可。如下:

  1. //把数据库中blob类型转换成String类型
  2. public String convertBlobToString(Blob blob){
  3. String result = "";
  4. try {
  5. ByteArrayInputStream msgContent =(ByteArrayInputStream) blob.getBinaryStream();
  6. byte[] byte_data = newbyte[msgContent.available()];
  7. msgContent.read(byte_data, 0,byte_data.length);
  8. result = new String(byte_data);
  9. } catch (SQLException e) {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. return result;
  14. }

相关内容