使用C#获取插入行的id

我有一个查询要在表中插入一行,该表有一个名为ID的字段,该字段使用列上的AUTO_INCREMENT填充。 我需要为下一部分function获取此值,但是当我运行以下操作时,即使实际值不为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()); 

根据我的理解,这应该返回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();" 

我明白了:

 {"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"} 

[编辑:在引用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()); 

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


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

 comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();", insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID); 
 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 

使用LastInsertedId。

通过示例查看我的建议: http : //livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/

让我感到困扰的是看到有人拿着Date并将它作为String存储在数据库中。 为什么列类型不能反映现实?

我也很惊讶看到使用字符串连接构建SQL查询。 我是一名Java开发人员,我根本不知道C#,但我想知道在库中的某个地方是否存在java.sql.PreparedStatement的绑定机制? 建议用于防范SQL注入攻击。 另一个好处是可能的性能优势,因为SQL可以被解析,validation,缓存一次并重用。

实际上,ExecuteScalar方法返回返回的DataSet的第一行的第一列。 在你的情况下,你只是在做一个插入,你实际上并没有查询任何数据。 您需要在插入后查询scope_identity()(这是SQL Server的语法)然后您将得到答案。 看这里:

连锁

编辑:正如迈克尔哈伦指出的那样,你在标签中提到你正在使用MySql,请使用last_insert_id(); 而不是scope_identity();