簡體   English   中英

Java Oracle:將TreeMap存儲為BLOB嗎?

[英]Java Oracle: Storing a TreeMap as BLOB?

我有以下代碼:

  public void StoreMapInDB(TreeMap<DateTime, Integer> map) throws
        IOException, FileNotFoundException{
    try {
  PreparedStatement insertMap = null;
  String insertString = "INSERT INTO TESTMAP(ID, NAME) VALUES (1, ?)";
  Connection con=null;
  con.setAutoCommit(false);
  Class.forName("oracle.jdbc.driver.OracleDriver");
  con=DriverManager.getConnection(
    "jdbc:oracle:thin:@XXXXX",
    "XXX",
    "XXX");
    //This line is incorrect for sure 
    //insertMap.setBlob(1, map.);
    } catch(Exception e){e.printStackTrace();}
}

連接正常,並且全部與數據庫一起使用。 這次,我試圖將地圖(即我創建的樹圖)插入到類型為BLOB的表的列中。 我怎樣才能做到這一點? 我還有其他更好的數據類型嗎?

謝謝,

如果要將對象放入BLOB數據類型,可以執行以下操作:

// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
PreparedStatement prepareStatement = connection.prepareStatement("insert into tableName values(?,?)");
prepareStatement.setLong(1, id);
prepareStatement.setBinaryStream(2, new ByteArrayInputStream(buf), buf.length);

有兩種方法可以解決此問題...

  • 您可以利用集合可序列化的事實,並將它們輸出到字節數組,如對此問題的答案所示。

  • 您可以更改表的類型,以便將鍵和值存儲為單獨的行,而不是使用二進制字段存儲TreeMap的特定實現,然后將其提取並用於以后重新構建地圖。 此選項更具前瞻性,因為您將不會永遠依賴TreeMap及其序列化格式。 而不是使用列(id, data) ,而是使用(id, key, value) 要保存到數據庫,請遍歷Map的entrySet()並使用相同的行ID插入每個鍵/值對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM