2011-08-12 70 views
1

我使用sqlite和java作爲編程語言。我有一類是Sqlite數據類型

public class DataSet { 

    public ArrayList<Double> a = null; 
    public ArrayList<Double> b = null; 
    public ArrayList<Double> c = null; 

    public DataSet() { 
     a = new ArrayList<Double>(); 
     b = new ArrayList<Double>(); 
     c = new ArrayList<Double>(); 
    } 
} 

我想存儲DATA,其中DataSet DATA=new DataSet(); SQLite中。但我期待這樣做一次不是在for循環中獲取數據一個接一個)。是否有任何數據集可以使用它並將整個事物存儲爲C#中的圖像?

+1

什麼是「數據」在這裏? –

+0

DATA是來自DataSet類的對象。 DataSet DATA = new DataSet(); – SunyGirl

+1

循環中出現什麼問題?你爲什麼需要一次性寫下它?你是否想要獲得SQLite事務的好處? – jefflunt

回答

2

你想存儲像一個圖像的對象?所以,作爲一個整體...讓對象序列化是這樣的:

public class DataSet implements Serializable { 
    /* this is the version of this class, 
    increment, when you change the implementation */ 
    public static final serialVersionUID = 1L; 
    ... 
} 

和二進制結果存儲到一個字節數組與ObjectOutputStream。這個字節數組可以作爲BLOB保存到數據庫中。例如,如果你的表有一個id和一個數據列:

byte[] data; 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
ObjectOutputStream oos = new ObjectOutputStream(bos); 
try { 
    oos.writeObject(DATA); 
    data = bos.toByteArray(); 
} finally { 
    oos.close(); 
}  

PreparedStatement pstmt = jdbcConnection.prepareStatement(
    "insert into MYTABLE (id, data) values (?, ?)"); 
pstmt.setLong(1); 
pstmt.setBlob(2, new ByteArrayInputStream(data)); 

... 

提交數據,關閉連接。警告:此代碼未經測試...

從數據庫中再次讀取blob,您可以使用從BLOB獲得的字節數組上的ObjectInputStream,就像上面的其他方法一樣。我留給你代碼。

請記住,以序列化的方式存儲數據不會是人類可讀的,所以你不能打開你的SQLite,查看它,並找出你的數據是否合理。

祝你好運!

+0

非常感謝:)它完美的作品! – SunyGirl

+0

不客氣。高興聽到! –