I have the following code:
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();}
}
The connection works and all with database. This time i am trying to insert the map ie the treemap i created into a column in the table with type BLOB. How can I do that? is there any other better datatypes that I should look into?
Thanks,
If you want to put your object into BLOB datatype, You could do something like this:
// 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);
There are two ways you can go about this...
You can take advantage of the fact that the collections are serializable and output them to a byte array, as shown in the answer to this question .
You could change the type of your table so that instead of using a binary field to store a specific implementation of a TreeMap, you store the keys and values as individual rows that can then be extracted and used to rebuild the map later. This option is more future-proof because you won't rely on TreeMap
and its serialization format forever. Instead of using the columns (id, data)
, you would use (id, key, value)
. To save to the DB, you iterate over the Map's entrySet()
and insert each key/value pair using the same row ID.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.