2017-02-26 15 views
-2

SQLクエリにパラメータ化された挿入を使用しようとしています。私は質問の数を追加しようとしていますINSERT INTO MySQL文のエラーC#

cmd.ExecuteNonQuery(); 

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; 
     } 

ライン私は '致命的な' というエラーを取得していますが、このコードを使用していますユーザーがフィールド「test_results」に正しく入力した(correctAnswers)

EDIT:

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

cannot implicitly convert type string to int

私はこれを取得していますなぜ私は知っているが、私は何をすべきか分かりません。

+7

。 –

+0

この問題を解決するにはどうすればよいですか? – CsharpStudent

+4

姓は一貫していますか?私のコメントを注意深く読んで、コードを注意深く読んで、パラメータ化されたSQLの仕組みを慎重に検討してください。あなたのSQLの名前があなたの 'Parameters'コレクションのパラメータの名前と一致しない場合、どのように動作すると思いますか? –

答えて

2

パラメータ名は、そのパラメータの値を設定するときに同じである必要があります。私はあなたがよく見てみると、私はそれを移植するときに、文のtestResults` @パラメータ `、と` @のtest_results`と呼ばれてきたからだと思われる場合の詳細は例外であります見つけることが疑われる

 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);のようなコードを変更してください。 ' –

+0

よかった、完了しました – CsharpStudent