.NET中获取Access新增记录Id怪现象解决方法

时间:2022-01-07 01:22:40

代码如下:


using System; 
using System.Data.OleDb; 
namespace ConsoleApplication1 

class Program 

static void Main(string[] args) 

Console.WriteLine(GetUserId("dnawo")); 
Console.ReadKey(); 

/// <summary> 
/// 获取用户Id 
/// </summary> 
/// <param name="name"></param> 
/// <returns></returns> 
static int GetUserId(string name) 

using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\db1.mdb")) 

conn.Open(); 
using (OleDbCommand cmd = new OleDbCommand()) 

cmd.Connection = conn; 
cmd.CommandText = "select Id from UserTB where UserName='" + name + "'"; 
object val = cmd.ExecuteScalar(); 
if (val != null) 
return int.Parse(val.ToString()); 
else 

cmd.CommandText = string.Format("insert into UserTB(UserName) values('{0}')", name); 
cmd.ExecuteNonQuery(); 
return GetUserId(name); 


conn.Close(); 




经测试,当用户不存在时,执行上边代码后Access表中总会新增两条一样的记录:

.NET中获取Access新增记录Id怪现象解决方法

改用SQL Server数据库不会有上述问题,经多次测试又发现,若在"return GetUserId(name);"处设置断点,稍停一会也不会出现上述问题。最终代码修改如下运行正常:

复制代码代码如下:


using System; 
using System.Data.OleDb; 
namespace ConsoleApplication1 

class Program 

static void Main(string[] args) 

Console.WriteLine(GetUserId("dnawo")); 
Console.ReadKey(); 

/// <summary> 
/// 获取用户Id 
/// </summary> 
/// <param name="name"></param> 
/// <returns></returns> 
static int GetUserId(string name) 

int id = 0; 
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\db1.mdb")) 

conn.Open(); 
using (OleDbCommand cmd = new OleDbCommand()) 

cmd.Connection = conn; 
cmd.CommandText = "select Id from UserTB where UserName='" + name + "'"; 
object val = cmd.ExecuteScalar(); 
if (val != null) 
id = int.Parse(val.ToString()); 
else 

cmd.CommandText = string.Format("insert into UserTB(UserName) values('{0}')", name); 
cmd.ExecuteNonQuery(); 


conn.Close(); 

return id == 0 ? GetUserId(name) : id;