`

公开一个Mysql如何获得新插入Id的代码

阅读更多
原理:
    在Mysql中同一个连接执行了insert语句,接着执行SELECT LAST_INSERT_ID()可以获得刚刚插入的自增。
    下面公开一段相关的Java代码

/**
	 * 执行插入操作并且获得新的Id
	 * 
	 * @param dataSource
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public static int insertAndGetId(DataSource dataSource, String sql, Object[] params)
			throws SQLException {
		Connection con = dataSource.getConnection();
		PreparedStatement pstmt = con.prepareStatement(sql);
		try {
			for (int i = 1; i <= params.length; i++) {
				pstmt.setObject(i, params[i - 1]);
			}
			pstmt.executeUpdate();
			ResultSet rs = pstmt.executeQuery("SELECT LAST_INSERT_ID()");
			rs.next();
			int newId = rs.getInt(1);
			rs.close();
			return newId;
		} finally {
			try {
				pstmt.close();
			} finally {
				con.close();
			}

		}

	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics