我在为游戏制作新角色时遇到此错误,在CreateCharHandler中发送“saveToDb(false);”但当我用另一个char我手动创建时,我可以saveToDb(true);没有错误。请帮忙,为什么会这样?
http://i56.tinypic.com/oh1pn5.png
SaveToDb方法 http://pastebin.com/9sT5XBxp
第3514行是 ResultSet rs = ps.getGeneratedKeys();提前致谢!
答案 0 :(得分:31)
您的SQLException
明确指出:
您需要指定
Statement.RETURN_GENERATED_KEYS
Statement.executeUpdate()
或Connection.prepareStatement()
。
这可以通过以下方式实现(在Connection.prepareStatement()
方法上添加额外的值):
String SQL = ""; //whatever my String is
PreparedStatement ps = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, "value");
//Other necessary ps.setXXX() methods
//now update
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
Statement.RETURN_GENERATED_KEYS
是关键所在。
希望这有帮助!
PS:Useful resource。
@Charlie berg,因为你喜欢懒惰,我更改了代码的第13行以包含Statement.RETURN_GENERATED_KEYS
:
ps = con.prepareStatement("INSERT INTO characters (level, fame, str, dex, luk, `int`, exp, hp, mp, maxhp, maxmp, sp, ap, gm, skincolor, gender, job, hair, face, map, meso, hpMpUsed, spawnpoint, party, buddyCapacity, messengerid, messengerposition, mountlevel, mounttiredness, mountexp, equipslots, useslots, setupslots, etcslots, monsterbookcover, watchedcygnusintro, vanquisherStage, dojopoints, lastDojoStage, finishedDojoTutorial, vanquisherKills, matchcardwins, matchcardlosses, matchcardties, omokwins, omoklosses, omokties, givenRiceCakes, partyquestitems, jailtime, accountid, name, world) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
此外,Statement
类是包java.sql
(确保正确导入)。 : - )
答案 1 :(得分:4)
如果没有指示应该进行自动生成的列 可供检索,对Statement.getGeneratedKeys的调用将 返回一个空的ResultSet。
您应明确告知JDBC您想要生成的密钥。
像这样:
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
或
conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
,然后您可以使用getGeneratedKeys()
。