2009-01-02 58 views
18

我有一個查詢將行插入到表中,該表有一個名爲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

回答

15

[編輯:添加 「選擇」 引用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

0

這困擾我看到有人採取日期並將其存儲在一個數據庫作爲字符串。爲什麼不讓列類型反映現實?

我也很驚訝地看到使用字符串連接構建的SQL查詢。我是一名Java開發人員,我根本不瞭解C#,但是我不知道庫中某處是否存在java.sql.PreparedStatement的綁定機制?建議用於防範SQL注入攻擊。另一個好處是可能的性能優勢,因爲SQL可以被解析,驗證,緩存一次並重用。

0

實際上,ExecuteScalar方法返回返回的DataSet的第一行的第一列。就你而言,你只是在做一個Insert,你實際上並沒有查詢任何數據。你插入後需要查詢scope_identity()(這是SQL Server的語法),然後你會得到你的答案。在這裏看到:

Linkage

編輯:正如邁克爾·哈倫指出,你在標籤中提到你使用MySQL,使用LAST_INSERT_ID();而不是scope_identity();

32
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