Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  


Insert with MS Access; return AutoNumber
C# Function to execute a SQL INSERT statement and return the recentmost Autonumber generated (for the insert). Since this is within a 'connection' it should be fairly autonomous. TODO: Find out whether it needs to be within a transaction as well.

/// Execute Insert Command against the Database.
/// INSERT command to execute
/// last generated AutoNumber value (for the insert)
public static int ExecuteInsert(string sqlText)
// establish a connection to an access database hosted on brinkster
System.Data.OleDb.OleDbConnection connection = Utilities.Connection;
int id = 0;
// Create the command object to perform the insert/update/delete command
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(sqlText, connection);
sqlText = "SELECT @@IDENTITY AS IDVal"; // get last autonumber
command = new System.Data.OleDb.OleDbCommand(sqlText, connection);
object o = command.ExecuteScalar();
id = Utilities.FromDB(o);
command = null;
catch(Exception e)
throw new System.Exception(sqlText + ", " + e.ToString());
// now close and destroy the connection object
connection = null;
return id;
} // insert

Created By: amos 3/20/2006 12:13:00 AM

 > Guest 12/23/2007 8:04:14 PM
thank you!!!