- String转成bolb插入到mysql数据库中
DbConn db=new DbConn();
Connection con=db.getConnection();
PreparedStatement pstmst = null;
ByteArrayInputStream stream = null;
try {
String sql = "insert into t values(?,1)";//?位置是blob类型的
pstmst =con.prepareStatement(sql);
String content = "aBc\nBBB";
stream = new ByteArrayInputStream(content.getBytes());
pstmst.setBinaryStream(1,stream,stream.available());
pstmst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
pstmst.close();
stream.close();
db.release(con);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2. 然后从数据库中读出blob再转成String;
DbConn db=new DbConn();
Connection con=db.getConnection();
PreparedStatement pstmst = null;
InputStream is = null;
ResultSet rs = null;
byte[] Buffer = new byte[4096];
String sql = "select config from t where id = ?";
pstmst =con.prepareStatement(sql);
pstmst.setInt(1, 1);
rs = pstmst.executeQuery();
if(rs.next())
{
is = rs.getBinaryStream("config");//config是blob类型的
}
int size = 0;
String result = "";
ByteArrayInputStream msgContent =(ByteArrayInputStream) rs.getBinaryStream("config");
byte[] byte_data = new byte[msgContent.available()];
msgContent.read(byte_data, 0,byte_data.length);
result = new String(byte_data);
System.out.println(result);