我在很多论坛上搜索过,但还没有找到我的问题的答案。我在这个网站上看到了与我有同样问题的人的相关主题,但大多数都使用了applet和servlet,我看不出与他们相比我做错了什么。
无论如何,关于我的问题。我最近刚开始学习MySQL,所以如果你看到任何可怕的东西,请原谅我。我正在尝试使用可序列化的对象,并将其写入MySQL中的表。从我做的研究中,我发现我需要使用BLOB作为字段,我需要使用byte []写入它。写作工作正常,没有问题,但当我尝试阅读时,我得到了上述错误。
我的写法:
public void addColonist(String p, Colonist c) {
// Serializing the Colonist
ByteArrayOutputStream baos;
baos = new ByteArrayOutputStream();
byte[] byteObject = null;
try {
out = new ObjectOutputStream(baos);
out.writeObject(c);
out.flush();
out.close();
baos.flush();
byteObject = baos.toByteArray();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
// Adding it to MySQL
sql.query("INSERT INTO colonistdb (`player`, `colonist`) VALUES('" + p + "', '" + byteObject + "')");
}
我的阅读/查找方法:
public Colonist getColonist(String p) {
// Getting the object from MySQL
ResultSet rs = sql.query("SELECT `colonist` FROM colonistdb WHERE `player` = '" + p + "'");
byte[] byteObject = null;
try {
if (rs.first()) {
byteObject = (byte[]) rs.getObject("colonist");
}
} catch (SQLException e) {
return null;
}
if (byteObject == null) {
System.out.println("byteObject is null");
return null;
}
// Deserializing it for use
ByteArrayInputStream bais;
Colonist colonist = null;
try {
bais = new ByteArrayInputStream(byteObject);
in = new ObjectInputStream(bais);
colonist = (Colonist) in.readObject();
in.close();
bais.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
System.out.println("Colonist successfully retrived");
return colonist;
}
从我在其他一些问题和帖子中读到的内容,我可能需要在我的read方法中创建一个ObjectOutputStream,但我试过这个没有用......
非常感谢任何帮助:)
答案 0 :(得分:2)
您插入的数据错误。您需要使用PreparedStatement才能使其正常工作。
PreparedStatement pstmt = sql.prepareStatement("INSERT INTO colonistdb (`player`, `colonist`) VALUES(?,?)");
pstmt.setString(1, p);
pstmt.setBytes(2, byteObject);
pstmt.executeUpdate();