Sql 插入记录返回主键id

有时候,我们的主键id是自动生成的,然后想要插入记录后,就取得这条记录的id,怎么做呢?

比如我现在的一个student表的字段为:id(PK autoIncrement), name, school, tel, password。这五个,现在我要插入一条记录,id是自动生成的, 不用传入。

应该这样:

Connection conn = null;
			int id = 0;
		try {
			conn = getConn();
			String sql = "insert into student(name,school,tel,password) values(?,?,?,?)";
			//String getId = "select "
			PreparedStatement ps =  conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);//获取到返回的id主键
			ps.setString(1, stu.getName());
			ps.setString(2, stu.getSchool());
			ps.setString(3, stu.getTel());
			ps.setString(4, stu.getPwd());
			int i = ps.executeUpdate();
			ResultSet rs = ps.getGeneratedKeys();
			if(rs.next()){
				id = rs.getInt(1);
			}
			System.out.println("ID:"+id);
			ps.close();
			conn.close();
			return id;
		}  catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;

PreparedStatement ps =  conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);

 ps.executeUpdate();

ResultSet rs = ps.getGeneratedKeys();

if(rs.next()){
id = rs.getInt(1);
}

你可能感兴趣的:(数据库知识碎碎片)