C#获取Access数据库新添加的数据ID

如果数据量比较大的话,重新查询整个数据表会影响程序性能,所以,只查询一条就好了….

/// <summary>
        /// 执行Insert语句,并返回新添加的记录ID
        /// </summary>
        /// <returns></returns>
        public object ExecuteNonQueryAndGetIdentity(string sql)
        {
            try
            {
                using (OleDbCommand com = new OleDbCommand(sql, con))
                {
                    if (com.ExecuteNonQuery() >= 1)
                    {
                        com.CommandText = "select @@identity";
                        return com.ExecuteScalar();
                    }
                    else
                    {
                        throw new Exception("记录添加不成功!");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 执行Insert语句,并返回新添加的记录ID
        /// </summary>
        public object ExecuteNonQueryAndGetIdentity(string sql, OleDbParameter par)
        {
            try
            {
                using (OleDbCommand com = new OleDbCommand(sql, con))
                {
                    com.Parameters.Add(par);
                    if (com.ExecuteNonQuery() >= 1)
                    {
                        com.CommandText = "select @@identity";
                        return com.ExecuteScalar();
                    }
                    else
                    {
                        throw new Exception("记录添加不成功!");
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 执行Insert语句,并返回新添加的记录ID
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="array"></param>
        /// <returns></returns>
        public object ExecuteNonQueryAndGetIdentity(string sql, ParametersArray array)
        {
            try
            {
                OleDbCommand com = new OleDbCommand(sql, con);
                SetParametersArray(ref com, array);
                if (com.ExecuteNonQuery() >= 1)
                {
                    com.CommandText = "select @@identity";
                    return com.ExecuteScalar();
                }
                else
                {
                    throw new Exception("记录添加不成功!");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

[buy] 可以添加到上一篇文章所写的类中使用[/buy]

6 Replies to “C#获取Access数据库新添加的数据ID”

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据