SunyGirl
SunyGirl

Reputation: 419

Sqlite datatype

I am using sqlite and java as programming language. I have a class which is

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

I want to store DATA, where DataSet DATA=new DataSet(); in sqlite. But I am looking to do it once( not in a for loop to get data one by one). Is there any dataset which I can use that and store the whole thing like an image in a C#?

Upvotes: 1

Views: 259

Answers (1)

Stefan Schubert-Peters
Stefan Schubert-Peters

Reputation: 5459

You want to store the object like an Image? So as a whole... Make the object Serializable like this:

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

And store the binary result into a byte array with an ObjectOutputStream. This byte array you can save into your database as a BLOB. For example if your table has an id and a data column:

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

...

Commit the data, close the connection. Warning: This code is not tested...

Reading the blob from the database again you can use an ObjectInputStream on the byte array you get from the BLOB just as above only the other way around. I leave that for you to code.

Please remember that storing data in a serialized way it will not be human-readable, so you can not open your SQLite, look into it and find out if your data is reasonable.

Good luck!

Upvotes: 2

Related Questions