题
我有一个查询要在表中插入一行,该表有一个名为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"}
解决方案
[编辑:添加“选择”在引用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);
其他提示
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可以被解析,验证,缓存一次并重用。
实际上,ExecuteScalar方法返回返回的DataSet的第一行的第一列。在你的情况下,你只是在做一个插入,你实际上并没有查询任何数据。您需要在插入后查询scope_identity()(这是SQL Server的语法),然后您将得到答案。见这里:
编辑:正如迈克尔哈伦指出的那样,你在标签中提到你正在使用MySql,请使用last_insert_id();而不是scope_identity();