C# を使用して挿入された行の ID を取得する 質問する

C# を使用して挿入された行の ID を取得する 質問する

テーブルに行を挿入するクエリがあります。このテーブルには 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"}

ベストアンサー1

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

おすすめ記事