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