2017-09-22 73 views
0

我有這種簡單的方法,應該將一行插入到數據庫中。它拋出了一個例外。SQL語句中的C#MySQL語法錯誤

private void AddToLiveQueue(int user_id, bool release = false) 
    { 
     string sql = "INSERT INTO live_support_queues (user_id, release, created_at, updated_at)"; 
     sql += " VALUES(?user_id, ?release, ?created_at, ?created_at)"; 

     MySqlConnection conn = new MySqlConnection(connString); 
     MySqlCommand cmd = conn.CreateCommand(); 
     cmd.CommandText = sql; 

     cmd.Parameters.AddWithValue("?user_id", user_id); 
     cmd.Parameters.AddWithValue("?release", release); 
     cmd.Parameters.AddWithValue("?created_at", DateTime.UtcNow); 


     try 
     { 
      conn.Open(); 
      cmd.ExecuteNonQuery(); 
      conn.Close(); 
     } 
     catch (Exception ex) 
     { 
      SendEmail email = new SendEmail(); 
      email.Send(ex.Message + "  " + ex.ToString()); 
     } 
    } 

我收到此錯誤:

"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 'release, created_at, updated_at) VALUES(70, 0, '2017-09-22 23:00:16.686741', '20' at line 1" 

Here is the SQL columns

任何幫助是極大的讚賞。謝謝!

+0

如果調試此,拉出來的值,準確的數據庫上運行的聲明,會發生什麼? – Seano666

+0

該ID是自動生成的,不在插入語句中。 user_is不是自動生成的,並且位於insert語句中。 –

+0

你能打印生成的SQL併發布嗎?這通常是一個很好的調試檢查。 –

回答

3

release是一個保留字,如果用作標識符,則需要使用符號進行轉義。

https://dev.mysql.com/doc/refman/5.7/en/keywords.html

+0

謝謝!我很感激。 –

+0

在將來當某個查詢不運行時,嘗試提取確切的查詢並運行它以進行測試......它將幫助您快速解決此類問題 –

+0

我發現最佳做法是使用';'分隔所有標識符。這樣,如果添加了新的保留字(或者可能導致某些含糊不清的關鍵字),那麼您已經覆蓋。 – Uueerdo