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

编程学习 2021-07-04 22:40www.dzhlxh.cn编程入门
写了一个函数获取Access表中指定用户Id,要求当传入的用户名不存在时,则在表中新增一条记录并返回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;
}
}
}

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板