欢迎光临

木子屋

标题: .NET获取Access新增记录Id怪现象

作者: dnawo

日期: 2012-03-01 05:09 PM

分类: Win编程

内容: 写了一个函数获取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;
}
}
}

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.723 ms

返回

标题: .NET获取Access新增记录Id怪现象

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.723 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.754 ms

返回