![]() |
|
![]() |
怎么存到数据库呢 写insert 行么 |
![]() 100分 |
这是插入:
public static void main(String[] args) {
String readSql = "insert into objects(id, object_bytes) values(1,?)";
try {
byte[] obs = getBytes();
PreparedStatement ps = conn.prepareStatement(readSql);
ps.setBytes(1, obs);
ps.execute();
ps.close();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
private static byte[] getBytes() throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(stream);
A a = new A();
a.age = 10;
a.name = "a10";
out.writeObject(a); //object是一个对象
out.flush();
out.close();
return stream.toByteArray();
}
这是查询反序列化:
public static void main(String[] args) {
String readSql = "select * from objects";
try {
PreparedStatement ps = conn.prepareStatement(readSql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
byte[] obs = rs.getBytes(2);
ByteArrayInputStream bis = new ByteArrayInputStream(obs);
ObjectInputStream ois = new ObjectInputStream(bis);
A a = (A) ois.readObject();
System.out.println(a.name);
}
ps.close();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
测试通过。 你对照下 |

