My little test-program is writing a serialized object into a mysql database, then retrieving it again, casting it to an object, then running it’s toString(). I’m trying to get the whole idea about Blobs on databases. (The object is a goat, that has a name, age and sex) My problem is that when I insert it into the database, it only sends the first byte, and not the rest.
First I write the object:
String query = "INSERT INTO goats(goat) VALUES (goat = ?)";
PreparedStatement pstmt = con.prepareStatement(query);
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(b);
out.writeObject(goat);
byte[] dataAsByteArray = b.toByteArray();
pstmt.setBinaryStream(1 , new ByteArrayInputStream(dataAsByteArray), dataAsByteArray.length);
Then I retrieve it again:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT goat FROM goats");
rs.next();
Blob blob = rs.getBlob(1);
byte[] bytes = blob.getBytes(1, (int) blob.length());
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
Thanks
Seems to be missing.
The answer seems to be that
goat=?is a boolean comparison yielding 0 or 1; a typo.VALUES(goat = ?)should beVALUES(?).