如何在java中将String转换为blob?

时间:2015-09-06 15:13:24

标签: java blob

我有一个包含大邮件正文的String。我需要以blob的形式将它保存到数据库中。如何将其转换为java中的blob? 下面的示例字符串:

<html><center> <body style='background-color: #e5e4e2;'> <table id='mainTable' style='background-color: #ffffff; width: 70%; height: auto;margin-left: auto; margin-right: auto;'><tr> <td> <table style='width: 100%;background-color: #2B547E; height: 50px; margin-top: 30px; margin-left: auto; margin-right: auto;'> <tr> <td width='50%'><img src="cid:image" height='50' width='150' style='padding-left: 10px;'></td> <td width='50%' style='text-align: right; color: white; font-family: verdana; font-size: 12px;'> </td></tr> </table> </td> </tr></table> <table id='mainTable1' style='background-color: #ffffff; width: 70%; height: auto;margin-left: auto; margin-right: auto;'> <tr> <td> <table style='width: 100%; height: 50px; margin-top: 30px; margin-left: auto; margin-right: auto;'><tr> <td width='50%' style='color:red;font-size:21px;'>Congratulations, Joselyn Valdes-Flores </td> <td width='50%' style='text-align: right; color: white; font-family: verdana; font-size: 12px;'> </td> </tr> <tr> <td style='font-size:18px;width:97%;font-style:italic'> This email confirms your Phone Interview  with Manager, Accounts Receivable  in   Burger King Corporation  You will be called at your mobile number </td> </tr> </table> </td> </tr> </table> <table  style='background-color: #ffffff; width: 70%; height: auto;margin-left: auto; margin-right: auto;'><tr style='color:green'> Interview LineUp <th style='color:gray;font-size:21px;text-align:left;font-style: italic'>Interviewe</th><th  style='color:gray;font-size:21px;text-align:left;font-style: italic'>Timing1</th><th  style='color:gray;font-size:21px;text-align:left;font-style: italic'>Timing2</th></tr><tr><td>Jeet Chatterjee</td><td>12:00am</td><td>2:00am</td></tr><tr><td>Ramu</td><td>2:00am</td><td>4:00am</td></tr></table><table id='mainTable2' style='background-color: #ffffff; width: 70%; height: auto;margin-left: auto; margin-right: auto; margin-top:12px;'><tr> <td style='font-size:18px; color:#2B547E;word-wrap: break-word;font-style: italic'> hii</td> </tr> </table> <table  style='background-color: #ffffff; width: 70%; height: auto;margin-left: auto; margin-right: auto;'> <tr> <td style='font-size:18px;color:#2B547E;word-wrap: break-word;font-style: italic'> Best Regards,</td><td style='font-size:24px;color:#2B547E;word-wrap: break-word;font-style: italic'> Jeet Chatterjee</td></tr> </table></body> </center> </html> 

我想将它保存在blob列的数据库中。怎么做??

2 个答案:

答案 0 :(得分:1)

您可以通过byte[]

获取String内容来实现此目的
byte[] byteData = yourString.getBytes("UTF-8");//Better to specify encoding
Blob blobData = dbConnection.createBlob();
blobData.setBytes(1, byteData);

此外,您可以直接将String存储到BLOB列。

答案 1 :(得分:0)

您可以首先使用以下方法从 byte[] 获取 String

byte[] byteData = yourString.getBytes();

然后执行下一行代码:

Blob docInBlob = new SerialBlob(byteData);

Blob 来自 java.sql 包,SerialBlob 来自 javax.sql.rowset.serial package