程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> .NET中獲取Access新增記錄Id怪現象解決方法

.NET中獲取Access新增記錄Id怪現象解決方法

編輯:ASP.NET基礎
復制代碼 代碼如下:
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;
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved