在SQL Server里有个全局变量 @@IDENTITY,他用来记录当前链接产生的自动加1的值,这个变量在access里也可以用,现在我们就用这个@@Identity在事务中获取新添加行的自动编号。需要注意的是获取自动编号的命令和插入记录的命令必须是在同一次打开数据库连接时执行否则Select @@Identity 返回为0。代码如下:
string sCon;
sCon = System.Configuration.ConfigurationManager.ConnectionStrings["access"].ConnectionString;
con = new OleDbConnection(sCon);
con.Open();
int i = -1;
OleDbCommand cmd = con.CreateCommand();
OleDbTransaction tr = con.BeginTransaction();
cmd.Transaction = tr;
cmd.CommandText = …………;
try
{
i = cmd.ExecuteNonQuery();
if (i > 0)
{
cmd.CommandText = @"select @@identity";
i = int.Parse(cmd.ExecuteScalar().ToString());
}
tr.Commit();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
this.Close();
return i;
sCon = System.Configuration.ConfigurationManager.ConnectionStrings["access"].ConnectionString;
con = new OleDbConnection(sCon);
con.Open();
int i = -1;
OleDbCommand cmd = con.CreateCommand();
OleDbTransaction tr = con.BeginTransaction();
cmd.Transaction = tr;
cmd.CommandText = …………;
try
{
i = cmd.ExecuteNonQuery();
if (i > 0)
{
cmd.CommandText = @"select @@identity";
i = int.Parse(cmd.ExecuteScalar().ToString());
}
tr.Commit();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
this.Close();
return i;