Conversion of java String and Blob Data
Data of the String type needs to be converted to Reader, and then inserted into the database using setCharacterStream.
For example, in the following example, to insert a String longStr, convert it to Byte [], then ByteArrayInputStream, and then InputStreamReader.
Add or update clob data, as shown in the following example ):
[Java] t = conn. prepareStatement ("update tablename set column1 =? "+ Condition statement );
Byte [] bytes_zyjs = longStr. getBytes ();
ByteArrayInputStream baisss = new ByteArrayInputStream (bytes_zyjs );
InputStreamReader bais = new InputStreamReader (baisss );
Pstmt. setCharacterStream (1, bais, bytes_zyjs.length );
Pstmt.exe cuteUpdate (); www.2cto.com
However, garbled characters are generated when writing Chinese characters in the preceding method. Therefore, the preceding method is mostly used in oracle, while mysql uses the setBinaryStream method. As long as the input location, inputstream, and length. Example:
[Java]
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); // you can directly write Chinese characters to read binary data; otherwise, garbled characters may occur.
Pstm. setBinaryStream (3, bais2, prikey_dataBytes.length );
Pcmd.exe cuteUpdate ();
Conn. commit ();
Conn. setAutoCommit (true );
Pstm. close ();
} Catch (SQLException e ){
E. printStackTrace ();
} Finally {
Try {
If (pstm! = Null)
Pstm. close ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
After reading Blob data from the database, convert it to String type, that is, convert it to InputStream, convert it from InputStream to byte [], and then to String. As follows:
[Java]
// Convert the blob type in the database to the String type
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;
}