how to get the last record number after inserting record to database in access

前端 未结 5 783
[愿得一人]
[愿得一人] 2021-02-05 21:40

i have database in access with auto increase field (ID).

i insert record like this (in C#)

SQL = \"insert into TermNumTbl (DeviceID,IP) valu         


        
5条回答
  •  春和景丽
    2021-02-05 22:15

    Using @Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:

    OleDbConnection con = new OleDbConnection(string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
    OleDbCommand cmd = con.CreateCommand();
    con.Open();
    cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
    cmd.Connection = con;
    cmd.ExecuteScalar();
    using (OleDbCommand command = new OleDbCommand("SELECT @@IDENTITY;", con))
    {
        ReturnIDCast =(int)command.ExecuteScalar();
    }
    

    NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.

提交回复
热议问题