復制代碼 代碼如下:
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;
}
}
}