【问题标题】:Java Oracle: Storing a TreeMap as BLOB?Java Oracle:将 TreeMap 存储为 BLOB?
【发布时间】:2012-01-14 01:53:29
【问题描述】:

我有以下代码:

  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 的列中。我怎样才能做到这一点?我应该研究其他更好的数据类型吗?

谢谢,

【问题讨论】:

    标签: java oracle oracle11g


    【解决方案1】:

    如果你想把你的对象变成 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);
    

    【讨论】:

    • hmmm...您能否详细说明您的最后一行,即“使用 buf 设置 Blob 数据类型?我尝试了一些方法,但怀疑它是否有效(尚未测试),即 Blob var = (Blob)map;
    • 哦刚刚试了一下,但是数据库没有在字段中得到任何更新。没有错误,但没有插入任何内容。有什么想法吗?
    • 您提交了事务还是打开了自动提交?如果是数据库问题,您很可能会收到异常返回。
    • 是的,我做了以下 con.commit();所以应该是因为我在开始时设置了 autocommit false
    • 你会调用prepareStatement.execute()吗?
    【解决方案2】:

    有两种方法可以解决这个问题...

    • 您可以利用集合可序列化这一事实并将它们输出到字节数组,如this question 的回答所示。

    • 您可以更改表的类型,而不是使用二进制字段来存储 TreeMap 的特定实现,而是将键和值存储为单独的行,然后可以提取并用于重建稍后地图。此选项更具前瞻性,因为您不会永远依赖TreeMap 及其序列化格式。您将使用(id, key, value),而不是使用列(id, data)。要保存到数据库,您需要遍历 Map 的 entrySet() 并使用相同的行 ID 插入每个键/值对。

    【讨论】:

    • 谢谢伙计,但如果我决定按照你的方式做,还有其他问题需要解决。问题是从映射访问的值和键对某些方法至关重要。所以也许我只是保持这种方式并序列化:)感谢您提出参考帖子:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2010-11-06
    • 1970-01-01
    • 2013-04-17
    • 2013-12-09
    • 2021-11-23
    • 2014-08-24
    相关资源
    最近更新 更多