使用Struts2和Hibernate Framework将java.lang.String转换为java.sql.Blob

时间:2013-02-11 11:09:31

标签: oracle hibernate java-ee struts2 blob

有没有办法将java.lang.String转换为java.sql.Blob?

请帮助我,这是我的项目要求之一,只需将用户密码作为Blob格式存入数据库(oracle10g)

提前致谢!

1 个答案:

答案 0 :(得分:2)

我找到了这个例子。我看到你使用oracle db所以这可能会有所帮助

package mypackage1;
import java.text.*;
import java.sql.*;
import java.util.*;

public class BlobTest 
{
    public BlobTest()
    { }

    public static void main(String[] args)throws SQLException 
    {
       try {
           DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
           Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:rashmidb", "scott", "tiger");
           PreparedStatement ps = conn.prepareStatement("INSERT INTO BLOBTABLE VALUES (?)");
           oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false, oracle.sql.BLOB.DURATION_SESSION);
           String myStr = "To test if the string gets inserted into the blob column";
           byte[] buff = myStr.getBytes();
           myBlob.putBytes(1,buff);
           ps.setBlob(1, myBlob);
           int count = ps.executeUpdate();
           ps.close();
           conn.close(); 
    }
     catch (Exception e) {
                      e.printStackTrace();
     }
   }

}

full article

如果您使用休眠,请查看this