使用C#获取插入行的id

Eli*_*lie 23 c# mysql last-insert-id

我有一个查询要在表中插入一行,该表有一个名为ID的字段,该字段使用列上的AUTO_INCREMENT填充.我需要为下一部分功能获取此值,但是当我运行以下操作时,即使实际值不为0,它也始终返回0:

MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID +  ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
Run Code Online (Sandbox Code Playgroud)

根据我的理解,这应该返回ID列,但每次只返回0.有任何想法吗?

编辑:

当我跑:

"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
Run Code Online (Sandbox Code Playgroud)

我明白了:

{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
Run Code Online (Sandbox Code Playgroud)

pet*_*tra 38

MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement;  // Set the insert statement
comm.ExecuteNonQuery();              // Execute the command
long id = comm.LastInsertedId;       // Get the ID of the inserted item
Run Code Online (Sandbox Code Playgroud)

  • *LastInsertedId不是线程安全的.*如果另一个线程正在插入内容,LastInsertedId将返回与db的连接上的最后一个插入的id.因此,如果多个线程执行它(或者甚至将具有相同用户的进程分离到db),那么它将是错误的. (4认同)

Mic*_*ren 22

[编辑:在引用last_insert_id()之前添加"select"]

select last_insert_id();插入后运行" " 怎么样?

MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "  
    + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID +  ");";
    + "select last_insert_id();"

int id = Convert.ToInt32(comm.ExecuteScalar());
Run Code Online (Sandbox Code Playgroud)

编辑:正如duffymo所提到的,使用像这样的参数化查询你会得到很好的服务.


编辑:直到你切换到参数化版本,你可能会发现与string.Format和平:

comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
  insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Run Code Online (Sandbox Code Playgroud)

  • 只是想注意,如果各个线程使用共享连接,Ted是正确的.如果每个线程都建立了它自己的连接,它应该运行得很好,因为mysql在每个连接的基础上处理它.[last_insert_id()documentation](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id) (3认同)