Access新增记录Id .NET中获取Access新增记录Id怪现象解决办法
人气:0想了解.NET中获取Access新增记录Id怪现象解决办法的相关内容吗,在本文为您仔细讲解Access新增记录Id的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Access,新增记录,Id,下面大家一起来学习吧。
复制代码 代码如下:
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表中总会新增两条一样的记录:
改用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;
}
}
}
加载全部内容