返回生成的主键

返回生成的主键


通过一个重载的prepareStatement(sql,int)来设置是否返回由数据库生成的主键,然后再使用ps.getGeneratedKeys()来获得包含主键的结果集。

  • preparedStatement
PreparedStatement ps=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.execute();
ResultSet keys=ps.getGeneratedKeys();
  • Statement
Statement st=conn.createStatement();
st.execute(sql,int autoGeneratedKeys);

示例:

public class Emp{
	public static void main(String[] args){
		register("李凌",new String[]{"抽烟","广场舞","皮"});
	}
	public static void register(String name,String[] hobby){
		String sql1="insert into emp(ename) values(?)";
		String sql2="insert into hobby values(null,?,?)";
		Connection conn=jdbcUtil.getConnection();//jdbcUtil为jdbc封装
		conn.setAutoCommit(false);
		try(PreparedStatement ps=conn.prepareStatement(sql1,Statement.RETURN_GENERATED_KEYS);
			PreparedStatement ps2=conn.prepareStatement(sql2);){
			ps.setString(1,name);
			ps.execute();
			ResultSet rs=ps.getGeneratedKeys();
			rs.next();
			int empno=rs.getInt(1);
			for(String s:hobby){
				ps2.setString(1,s);
				ps2.setInt(2,empno);
				ps2.execute();
			}
			conn.commit
		}catch(Exception e){
			e.printStackTrace();
			conn.rollback();
		}finally{
			conn.close();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/XV9216543/article/details/83795017