求Statement接口的RETURN_GENERATED_KEYS详解【JAVA】

来源:百度知道 编辑:UC知道 时间:2024/06/23 08:07:25
如题
API上如是说:
RETURN_GENERATED_KEYS
static final int RETURN_GENERATED_KEYS该常量指示生成的键应该可用于检索。

但是不是很明白,具体到:
PreparedStatement pstmt = conn.prepareStatement("sql串",Statement.RETURN_GENERATED_KEYS)
怎么理解?返回的是什么?

获取自动生成的键值,int id primary key auto_increment;

Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:mysql://localhost/BBS?user=root&password=root"); //连接数据库
conn.setAutoCommit(false); //不自动提交

String sql = "insert into article values (null,0,?,?,?,now(),0)";
PreparedStatement pstat = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

//创建一个默认 PreparedStatement 对象,该对象能获取自动生成的键,适合insert语句

//(该语句能自动生成键值)autoGeneratedKeys - 指示是否应该返回自动生成的键的标志

//它是 Statement.RETURN_GENERATED_KEYS 或 Statement.NO_GENERATED_KEYS 之一

Statement stat = conn.createStatement();

pstat.setInt(1, -1);
pstat.setString(2,title);
pstat.setString(3,content);
pstat.executeUpdate();

ResultSet rsKey = pstat.getGeneratedKeys(); //ResultSet 指示键值
rsKey.next();
int key = rsKey.getInt(1); //得到第一个