java · jdbc · mysql

how to get last insert id by java

	public static int getLastInsertID(Connection conn, String statment)throws SQLException {
		int lastInsertedId = -1;
		PreparedStatement ps = conn.prepareStatement(statment,PreparedStatement.RETURN_GENERATED_KEYS);
		ps.executeUpdate();

		ResultSet rskey = ps.getGeneratedKeys();
		if (rskey != null && rskey.next()) {
			lastInsertedId = rskey.getInt(1);
		}
		return lastInsertedId;
	}
Advertisements