我有以下代码:

  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);

10-06 02:12