java将blob转换成string

来源:互联网 发布:金星跟老公 知乎 编辑:程序博客网 时间:2024/05/30 13:42

需要把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;
 }