【问题标题】:SQLException - Generated keys not requested (MySQL)SQLException - 未请求生成的密钥 (MySQL)
【发布时间】:2011-11-02 01:00:52
【问题描述】:

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

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

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

第 3514 行是:

ResultSet rs = ps.getGeneratedKeys();

提前致谢!

【问题讨论】:

  • 嗨,查理,由于外部链接往往会衰减和消失(尤其是 pastebin),因此最好在问题中直接包含您想要显示的代码和图片。您可以通过单击评论框正上方的编辑来做到这一点。

标签: java mysql


【解决方案1】:

您的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 包(确保正确导入)。 :-)

【讨论】:

  • 感谢您的帮助!但不幸的是,我不明白-facepalm-您能否告诉我要更改我的代码的内容,并保证我会学习:D。泰蒂
  • @Charlie berg,只需将第 13 行更改为此(看看我如何将 Statement.RETURN_GENERATED_KEYS 添加到您的 con.prepareStatement
【解决方案2】:

Oracle Documents:

如果没有指示应该创建自动生成的列 可用于检索,对 Statement.getGeneratedKeys 的调用将 返回一个空结果集。

你应该明确告诉 JDBC 你想要生成的密钥。

像这样:

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

conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

然后你可以使用getGeneratedKeys()

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2018-01-21
    • 2012-12-16
    相关资源
    最近更新 更多