I need a function which executes an INSERT statement on a database and returns the Auto_Increment primary key. I have the following C# code but, while the INSERT statement w
The short answer:
1. Create two commands each accepting a single query.
2. First sql query is the INSERT record.
3. Second sql query is "SELECT @@Identity;" which returns the AutoNumber.
4. Use cmd.ExecuteScalar() which returns a first column of first row.
5. The returned result output is the AutoNumber value generated in the current insert query.
It is referenced from this link. The example code is as under. Note the difference for "SAME Connection VS NEW Connection". The SAME Connection gives the desired output.
class Program
{
static string path = @"";
static string db = @"Test.mdb";
static void Main(string[] args)
{
string cs = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}\{1}", path, db);
// Using the same connection for the insert and the SELECT @@IDENTITY
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
for (int i = 0; i < 3; i++)
{
cmd.CommandText = "INSERT INTO TestTable(OurTxt) VALUES ('" + i.ToString() + "')";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT @@IDENTITY";
Console.WriteLine("AutoNumber: {0}", (int)cmd.ExecuteScalar());
}
con.Close();
}
// Using a new connection and then SELECT @@IDENTITY
using (OleDbConnection con = new OleDbConnection(cs))
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT @@IDENTITY";
Console.WriteLine("\nNew connection, AutoNumber: {0}", (int)cmd.ExecuteScalar());
con.Close();
}
}
}
This should produce the self-explanatory output:
AutoNumber: 1
AutoNumber: 2
AutoNumber: 3
New connection, AutoNumber: 0