2013-06-26 24 views
8

1.Come creare un oggetto BLOB in java?
2.Come impostare il valore BLOB da db?
3.Come impostare il valore BLOB nel DB?
Come creare un oggetto BLOB in java?

devo creare l'oggetto BLOB come

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

Ma mi dà error..So favore, qualcuno mi aiuti. Grazie in anticipo.

+0

Perché è necessario creare un oggetto BLOB? O vuoi leggere i dati BLOB dal DB? – NINCOMPOOP

+0

Sto recuperando un valore BLOB da db e voglio salvare questo valore nell'oggetto BLOB è per questo che voglio creare un oggetto.Dopo averlo salvato di nuovo voglio salvare questo valore in un altro db in quel momento voglio ottenere quel valore.I sto usando la struttura di primavera. – vijayk

+0

possibile duplicato di [Inserisci BLOB usando java per DB2 e Oracle] (http://stackoverflow.com/questions/16462060/insert-blob-using-java-for-both-db2-and-oracle) –

risposta

20

1) per creare BLOB uso Connection.createBlob

2) di scrivere BLOB a DB utilizzare PreparedStatement.setBlob

3) per leggere BLOB da DB uso ResultSet.getBlob

Supponendo di avere tabella t1 con BLOB colonna 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

OK vedi aggiornato risposta –