您的位置:首页 > 博客中心 > 数据库 >

获取ACCESS数据库中自增变量的值

时间:2022-03-10 17:43

/// <summary>
        /// 获取自增变量值
        /// </summary>
        /// <returns>自增变量值</returns>
        public int getReturnIdentity()
        {
            //Conn_Open();
            string strCMDtext = @"select @@identity";
            OleDbCommand cmd_sql = new OleDbCommand(strCMDtext, conn_1);
            int i = int.Parse(cmd_sql.ExecuteScalar().ToString());
            cmd_sql.Dispose();
            return i;
            //conn_close();
        }




  (转自http://www.cnblogs.com/hongyuniu/archive/2008/03/08/1096638.html) 在SQL Server里有个全局变量 @@IDENTITY,他用来记录当前链接产生的自动加1的值,这个变量在access里也可以用,现在我们就用这个@@Identity在事务中获取新添加行的自动编号。需要注意的是获取自动编号的命令和插入记录的命令必须是在同一次打开数据库连接时执行否则Select @@Identity 返回为0。代码如下:

gxlsystem.com,布布扣string sCon;
gxlsystem.com,布布扣sCon = System.Configuration.ConfigurationManager.ConnectionStrings["access"].ConnectionString;
gxlsystem.com,布布扣con = new OleDbConnection(sCon);
gxlsystem.com,布布扣con.Open();
gxlsystem.com,布布扣            int i = -1;
gxlsystem.com,布布扣            OleDbCommand cmd = con.CreateCommand();
gxlsystem.com,布布扣            OleDbTransaction tr = con.BeginTransaction();
gxlsystem.com,布布扣            cmd.Transaction = tr;
gxlsystem.com,布布扣            cmd.CommandText = …………;
gxlsystem.com,布布扣            try
gxlsystem.com,布布扣            {
gxlsystem.com,布布扣                i = cmd.ExecuteNonQuery();
gxlsystem.com,布布扣                if (i > 0)
gxlsystem.com,布布扣                {
gxlsystem.com,布布扣                    cmd.CommandText = @"select @@identity";
gxlsystem.com,布布扣                    i = int.Parse(cmd.ExecuteScalar().ToString());
gxlsystem.com,布布扣                }
gxlsystem.com,布布扣                tr.Commit();
gxlsystem.com,布布扣            }
gxlsystem.com,布布扣            catch (Exception e)
gxlsystem.com,布布扣            {
gxlsystem.com,布布扣                
gxlsystem.com,布布扣                MessageBox.Show(e.Message);
gxlsystem.com,布布扣            } 
gxlsystem.com,布布扣            this.Close();
gxlsystem.com,布布扣            return i;
gxlsystem.com,布布扣

 

获取ACCESS数据库中自增变量的值,布布扣,bubuko.com

热门排行

今日推荐

热门手游