使用C#获取插入行的ID

问题描述:

我有一个查询将行插入到表中,该表有一个名为ID的字段,该字段在列上使用AUTO_INCREMENT填充。我需要的功能下一位该值,但是当我运行下面的,它总是返回0即使实际值不为0:使用C#获取插入行的ID

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"} 
+0

1.你能张贴被执行最后的CommandText? 2。记录是否被插入? – 2009-01-02 03:20:19

+0

我发布了查询,错误,并且是,正在插入行。 – Elie 2009-01-02 03:24:50

+0

好的,如何“SELECT last_insert_id();”最后? – 2009-01-02 03:28:07

[编辑:添加 “选择” 引用LAST_INSERT_ID()之前]

如何在inser后面运行“select last_insert_id();” T'

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提到的,你真的会得到很好的使用参数化查询like this服务。


编辑:直到你切换到一个参数化的版本,你可能会发现和平与的String.format:

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

我会尝试没有它的查询。记录是否被插入? – 2009-01-02 03:10:04

+0

是的,记录正在插入。 – Elie 2009-01-02 03:23:14

这困扰我看到有人采取日期并将其存储在一个数据库作为字符串。为什么不让列类型反映现实?

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

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

Linkage

编辑:正如迈克尔·哈伦指出,你在标签中提到你使用MySQL,使用LAST_INSERT_ID();而不是scope_identity();

使用LastInsertedId。

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

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