26

我有一个查询要在表中插入一行,该表有一个名为 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());

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

5 回答 5

47
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
于 2013-02-06T11:07:33.140 回答
23

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

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);
于 2009-01-02T02:48:54.073 回答
3

使用 LastInsertedId。

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

于 2011-10-28T11:38:29.947 回答
0

看到有人拿日期并将其作为字符串存储在数据库中,我感到很困扰。为什么不让列类型反映现实?

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

于 2009-01-02T02:55:20.893 回答
0

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

连锁

编辑:正如 Michael Haren 指出的那样,您在标签中提到您正在使用 MySql,使用 last_insert_id(); 而不是 scope_identity();

于 2009-01-02T03:11:29.600 回答