@@IDENTITY after INSERT statement always returns 0

后端 未结 13 1179
一整个雨季
一整个雨季 2021-01-11 13:00

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

13条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 13:14

    If you would like to retrieve value of auto running number of transaction that you're inserting and your environment following 1. Database is MsAccess. 2. Driver is Jet4 with connection string like this "Provider=Microsoft.Jet.OLEDB.4.0;Password={0};Data Source={1};Persist Security Info=True" 3. use Oledb

    You can apply my example to your code

    OleDbConnection connection =  String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Password={0};Data Source={1};Persist Security Info=True",dbinfo.Password,dbinfo.MsAccessDBFile);
    connection.Open();
    OleDbTransaction transaction = null;
    try{
        connection.BeginTransaction();
        String commandInsert = "INSERT INTO TB_SAMPLE ([NAME]) VALUES ('MR. DUKE')";
        OleDbCommand cmd = new OleDbCommand(commandInsert , connection, transaction);
        cmd.ExecuteNonQuery();
        String commandIndentity = "SELECT @@IDENTITY";
        cmd = new OleDbCommandcommandIndentity, connection, transaction);
        Console.WriteLine("New Running No = {0}", (int)cmd.ExecuteScalar());
        connection.Commit();
    }catch(Exception ex){
        connection.Rollback();
    }finally{
        connection.Close();
    }   
    

提交回复
热议问题