假设我想通过JDBC向表中添加一个新行。在我的表中,我有一个自动递增的主键字段(所以我可以稍后更新表)和另一个常规字段。
userid BIGINT AUTO_INCREMENT PRIMARY KEY,
username TEXT,
现在,我正在创建新语句并使用预处理语句执行它,如下所示:
//dummy execute to get the generated keys
stmt.execute("SELECT * FROM user;", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
int id=1;
//this is never executed, the resultset is always empty...
if(rs.next())
{
System.out.println("not empty");
id = rs.getInt(1);
}
System.out.println(id); //therefore, id is always 1
//prepare a statement to execute in SQL
stmt=con.prepareStatement("INSERT INTO user VALUES (?,?);", Statement.RETURN_GENERATED_KEYS);
//fill in the ?'s with their respective values
((PreparedStatement) stmt).setString(1, String.valueOf(id));
((PreparedStatement) stmt).setString(2, user);
//execute statement
((PreparedStatement) stmt).executeUpdate();
如您所见,我想要生成的键的值,以便我可以使用预准备语句来更新新生成的行中的所有列(否则我会为参数1错误指定No值)。
但是当我执行上面的代码时,我得到了一个
Duplicate entry '1' for key 'PRIMARY'
在我看来,结果集总是空的。所以我没有正确访问该值。为什么会这样,我该如何解决这个问题,以便我可以使用相同的预准备语句结构来执行这些查询?
答案 0 :(得分:1)
只有在执行了您的陈述后才能呼叫getGeneratedKeys
,而不是之前。见https://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#getGeneratedKeys--
简单地准备语句不会生成新密钥。只需从插入中删除id列,然后只插入用户。
答案 1 :(得分:0)
1.由于您的ID是自动增量列,您应该首次传递该字段的值(尝试直接通过MYSQL
服务器执行此操作。
2.不要尝试对空结果集执行操作。
3.在你的情况下,id始终为1,因为if语句没有执行。
谢谢。