首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用C#获取插入行的id

使用C#获取插入行的id
EN

Stack Overflow用户
提问于 2009-01-02 02:40:05
回答 5查看 64K关注 0票数 26

我有一个向表中插入一行的查询,该表有一个名为ID的字段,该字段是使用列上的AUTO_INCREMENT填充的。我需要为下一步的功能获取这个值,但是当我运行以下命令时,即使实际值不是0,它也总是返回0:

代码语言:javascript
运行
复制
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。有什么想法吗?

编辑:

当我运行时:

代码语言:javascript
运行
复制
"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();"

我得到了:

代码语言:javascript
运行
复制
{"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"}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-01-02 02:48:54

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

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

代码语言:javascript
运行
复制
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很好用:

代码语言:javascript
运行
复制
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
  insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
票数 23
EN

Stack Overflow用户

发布于 2013-02-06 19:07:33

代码语言:javascript
运行
复制
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
票数 46
EN

Stack Overflow用户

发布于 2011-10-28 19:38:30

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/405910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档