使用PreparedStatement插入。如何自动递增ID? [英] Insert using PreparedStatement. How do I auto-increment the ID?

查看:388
本文介绍了使用PreparedStatement插入。如何自动递增ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PreparedStatement,例如:

I have a PreparedStatement such as:

 PreparedStatement preparedStatement = connect.prepareStatement("INSERT into employee (id, time, name" + "(?,?,?)",Statement.RETURN_GENERATED_KEYS);
 ResultSet tableKeys = preparedStatement.getGeneratedKeys();
 preparedStatement.executeUpdate();
 tableKeys.next();
 int autoGeneratedID = tableKeys.getInt(1);
 preparedStatement.setInt(1,autoGeneratedID);
 preparedStatement.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));                           
 preparedStatement.setString(3, "Test");
 preparedStatement.executeUpdate();

如您所见,Employee表有一个自动递增的ID。我需要基本上使用preparedStatement自动添加它。有人可以告诉我我要去哪里错误并纠正我?现在它只是给了我一个与Statement相关的错误。

As you can see, the Employee table has an auto-incremented ID. I need to basically add it in automatically using preparedStatement as well. Can someone tell me where I am going wrong and correct me? Right now it just gives me an error related to Statement.

推荐答案

将该列从 INSERT 语句完全中删除。它将由数据库引擎生成。您的查询应为:

Leave the column out of the INSERT statement entirely. It will be generated by the database engine. Your query should be:

INSERT INTO employee (time, name)
VALUES (?, ?)

其次,你必须先执行插入,然后从结果中取出密钥。

Secondly, you have to perform the insert first, then get the keys out of the result.

我相信你的代码应该是:

I believe your code should be:

PreparedStatement preparedStatement = 
    connect.prepareStatement("INSERT into employee (time, name) VALUES (?,?)", 
    Statement.RETURN_GENERATED_KEYS);

preparedStatement.setTimestamp(1, 
    new java.sql.Timestamp(new java.util.Date().getTime()));                           
preparedStatement.setString(2, "Test");

preparedStatement.executeUpdate();

ResultSet tableKeys = preparedStatement.getGeneratedKeys();
tableKeys.next();
int autoGeneratedID = tableKeys.getInt(1);

注意此示例不检查已执行语句的成功或返回键的存在。

Note this example does not check the success of the executed statement or the existence of returned keys.

这篇关于使用PreparedStatement插入。如何自动递增ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆