Copy Code code as follows:
Using System;
Using System.Data.OleDb;
Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
Console.WriteLine (GetUserID ("Dnawo"));
Console.readkey ();
}
<summary>
Get User 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 ();
}
}
}
}
After testing, when the user does not exist, after executing the top code, the Access table always adds two entries:
Using a SQL Server database will not have the above problems, and has been repeatedly tested and found in the "return GetUserID (name);" To set a breakpoint, stop for a moment and there will be no such problem. The final code is modified to run normally as follows:
Copy Code code as follows:
Using System;
Using System.Data.OleDb;
Namespace ConsoleApplication1
{
Class Program
{
static void Main (string[] args)
{
Console.WriteLine (GetUserID ("Dnawo"));
Console.readkey ();
}
<summary>
Get User 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;
}
}
}