To get the value of a self-increment variable in an Access database

Source: Internet
Author: User
Tags access database

/// <summary>        ///get self-increment variable value/// </summary>        /// <returns>self-increment variable value</returns>         Public intgetreturnidentity () {//Conn_open ();            stringstrCmdText =@"SELECT @ @identity"; OleDbCommand Cmd_sql=NewOleDbCommand (strCmdText, conn_1); inti =int. Parse (Cmd_sql. ExecuteScalar ().            ToString ()); Cmd_sql.            Dispose (); returni; //conn_close ();}

Get automatic numbering of newly added rows in Access (go from in SQL Server there is a global variable @ @IDENTITY, he used to record the current link generated by the Auto plus 1 value, this variable can also be used in access, and now we use this @ @Identity in the transaction to get the new added row of the automatic numbering. Note that the command to get the AutoNumber and insert the record must be executed at the same time that the database connection is opened or the SELECT @ @Identity returns 0. The code is as follows:

String SCon;
SCon = system.configuration.configurationmanager.connectionstrings["Access". ConnectionString;
con = new OleDbConnection (SCon);
Con. Open ();
int i =-1;
OleDbCommand cmd = con. CreateCommand ();
oledbtransaction tr = con. BeginTransaction ();
Cmd. Transaction = TR;
Cmd.commandtext = ...;..;
i = cmd. ExecuteNonQuery ();
if (i > 0)
Cmd.commandtext = @ "SELECT @ @identity";
i = Int. Parse (cmd. ExecuteScalar (). ToString ());
Tr.commit ();
catch (Exception e)

MessageBox.Show (E.message);
This. Close ();
return i;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.