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

2022-09-02 23:10:04

当我为我的游戏制作一个新角色时,我得到这个错误,在CreateCharHandler中,它发送“saveToDb(false);”但是当我与另一个字符在游戏中时,我手动创建,我可以保存ToDb(true);没有错误。请帮忙,为什么会这样?

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

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

第 3514 行是:

ResultSet rs = ps.getGeneratedKeys();

提前致谢!


答案 1

您明确指出: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();

这是关键。Statement.RETURN_GENERATED_KEYS

希望这有帮助!

PS:有用的资源


@Charlie伯格,因为你更喜欢懒惰,我改变了你的代码的第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);

此外,类是包(确保正确导入)。:-)Statementjava.sql


答案 2

甲骨文文档

如果没有指示应使自动生成的列可用于检索,则对 Statement.getGeneratedKeys 的调用将返回空 ResultSet。

您应该明确告诉 JDBC 您需要生成的密钥。

喜欢这个:

Statement stmt = conn.createStatement();
stmt.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);

conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

然后您可以使用.getGeneratedKeys()


推荐