将该列 完全 放在INSERT语句之外。它将由数据库引擎生成。您的查询应为: __
INSERT INTO employee (time, name)VALUES (?, ?)
其次,您必须先执行插入操作,然后再从结果中取出密钥。
我相信您的代码应为:
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);
请注意,此示例不检查执行的语句是否成功或返回的键是否存在。
解决方法我有一个PreparedStatement,例如:
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。我基本上也需要使用prepareStatement自动添加它。有人可以告诉我我要去哪里哪里并纠正我吗?现在,这只是给我一个与Statement相关的错误。