2013-06-26 146 views
8

1.如何在java中創建BLOB對象?
2.如何從db中設置BLOB值?
3.如何在數據庫中設置BLOB值?
如何在java中創建BLOB對象?

我已創建像

byte [] fileId=b.toByteArray(); 
    Blob blob=new SerialBlob(fileId); 

的BLOB對象,但它給了我error..So請任何一個幫助我。 在此先感謝。

+0

爲什麼你需要創建一個BLOB對象?或者你想讀取數據庫中的BLOB數據? – NINCOMPOOP

+0

我正在從數據庫中獲取一個BLOB值,並且我想將這個值保存在BLOB對象中,這就是爲什麼我想創建一個對象。再次保存後,我想將該值保存在另一個數據庫中,那個時候我想獲得該值。我正在使用spring框架。 – vijayk

+0

[使用Java爲DB2和Oracle插入BLOB]可能的重複(http://stackoverflow.com/questions/16462060/insert-blob-using-java-for-both-db2-and-oracle) –

回答

20

1)創建BLOB使用Connection.createBlob

2)寫入BLOB到DB使用PreparedStatement.setBlob

3)來讀取數據庫使用ResultSet.getBlob

BLOB假設你有表t1與BLOB列b1:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); 
    Blob b1 = conn.createBlob(); 
    b1.setBytes(1, new byte[10]); // first position is 1. Otherwise you get: Value of offset/position/start should be in the range [1, len] where len is length of Large Object[LOB] 

    PreparedStatement ps = conn.prepareStatement("update t1 set c1 = ?"); 
    ps.setBlob(1, b1); 
    ps.executeUpdate(); 

    Statement st = conn.createStatement(); 
    ResultSet rs = st.executeQuery("select c1 from t1"); 
    Blob b2 = rs.getBlob(1); 
+0

確定請參閱已更新回答 –