SQLException - 未请求生成的密钥(MySQL)

Cha*_*erg 13 java mysql

当我为我的游戏制作一个新角色时,我收到此错误,在CreateCharHandler中它发送"saveToDb(false);" 但当我用另一个char我手动创建时,我可以saveToDb(true); 没有错误.请帮忙,为什么会这样?

http://i56.tinypic.com/oh1pn5.png

SaveToDb方法 http://pastebin.com/9sT5XBxp

第3514行是ResultSet rs = ps.getGeneratedKeys();

提前致谢!

Buh*_*ndi 38

SQLException明确指出:

你需要指定Statement.RETURN_GENERATED_KEYSStatement.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();
Run Code Online (Sandbox Code Playgroud)

Statement.RETURN_GENERATED_KEYS是关键.

希望这可以帮助!

PS:有用的资源.


@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);
Run Code Online (Sandbox Code Playgroud)

此外,Statement类是包java.sql(确保您正确导入).:-)