1。 [b]如果需要拿到插入数据后自动生成的ID值,可以在插入操作中要求返回ID值,Statement.RETURN_GENERATED_KEYS。[/b]
如要拿到以下表中user_id值。
对于java.sql.Statement,在执行操作时指定。
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS)
对于java.sql.PreparedStatement,在生成语句对象时指定。
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
获取返回的ID值。
ResultSet rs = stmt.getGeneratedKeys();
rs.getInt(1);
如果没有指定要求ID值,却调用方法getGeneratedKeys(),会出现如下异常。
java.sql.SQLException: !Statement.GeneratedKeysNotRequested!
如要拿到以下表中user_id值。
create table foo
(
user_id int not null auto_increment PRIMARY KEY,
name varchar(50)
)
对于java.sql.Statement,在执行操作时指定。
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS)
对于java.sql.PreparedStatement,在生成语句对象时指定。
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
获取返回的ID值。
ResultSet rs = stmt.getGeneratedKeys();
rs.getInt(1);
如果没有指定要求ID值,却调用方法getGeneratedKeys(),会出现如下异常。
java.sql.SQLException: !Statement.GeneratedKeysNotRequested!