JAVA向数据库插入数据返回ID值的方法

java.sql.Statement 返回键获取:
1.使用JDBC 3.0提供的 getGeneratedKeys (推荐使用)
	Statement stmt = conn.createStatement();
	stmt.executeQuery("INSERT INTO table_name(...) values(...)",Statement.RETURN_GENERATED_KEYS);
	ResultSet rs = stmt.getGeneratedKeys();
	if(rs.next()){
		this.setId(rs.getInt(1));
		}

2.使用特定数据库特有的SQL
Statement stmt = conn.createStatement();
stmt.executeQuery("INSERT INTO table_name(...) values(...)",Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
if(rs.next()){
      this.setId(rs.getInt(1));
}

你可能感兴趣的:(java)