2017-02-26 111 views
-2

我想使用參數化插入到SQL查詢中。我已經使用這個代碼,但是我得到一個 '致命' 的錯誤:INSERT INTO MySQL語句錯誤C#

An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll

Additional information: Fatal error encountered during command execution.

C#代碼:

 using(MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=root;password=***;")) 
     { 
      MySqlCommand cmd = new MySqlCommand("INSERT INTO test_results (test_results) VALUES (@testResults);"); 
      cmd.CommandType = CommandType.Text; 
      cmd.Connection = connection; 
      cmd.Parameters.AddWithValue("@test_results", correctAnswers); 
      connection.Open(); 
      cmd.ExecuteNonQuery(); 
      cmd.Connection = connection; 
     } 

線:

cmd.ExecuteNonQuery(); 

我想補充的問題的數量(correctAnswers)用戶正確進入「test_results」字段

編輯:

int topicID = dataGridViewRow.Cells["topicID"].Value.ToString(); 

cannot implicitly convert type string to int

我知道爲什麼我收到這個,但我不知道我應該做的。

+7

我填充時,懷疑你會發現有更多的信息,在異常,如果你仔細看,我懷疑這是因爲你叫語句中的參數'@ testResults'和'@ test_results' 。 –

+0

所以我應該如何修改我的代碼來解決這個問題? – CsharpStudent

+4

恩,使用一致的名字?仔細閱讀我的評論,仔細閱讀您的代碼,並仔細考慮參數化SQL的工作原理。如果您的SQL中的名稱與您的'Parameters'集合中的參數名稱不匹配,您如何期待它的工作? –

回答

2

當您爲該參數設置值時,參數名稱必須相同。

 using(MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=root;password=***;")) 
    { 
     MySqlCommand cmd = new MySqlCommand("INSERT INTO test_results (test_results) VALUES (@testResults);"); 
     cmd.CommandType = CommandType.Text; 
     cmd.Connection = connection; 
     cmd.Parameters.AddWithValue("@testResults", correctAnswers); 
     connection.Open(); 
     cmd.ExecuteNonQuery(); 
     cmd.Connection = connection; 
    } 
+0

@Huesyn Alizada你可以檢查我編輯的問題的底部:) plz – CsharpStudent

+0

你應該將其轉換爲int。像這樣改變你的代碼'int topicID = Convert.ToInt32(dataGridViewRow.Cells [「topicID」]。Value); ' – 2017-02-26 16:39:32

+0

很好,幹得好 – CsharpStudent