2016-05-15 1 views
-1

書き込み値が計算された後に、calorie_trackerテーブルを更新したいと思います。cmd2コマンドを使用すると動作しますが、cmd2を実行しようとするとエラーが発生します。 object.このコマンドを同じコマンド(cmd)で更新する方法はありますか?MySqlCommandオブジェクト参照がオブジェクトのインスタンスに設定されていません

string time = DateTime.Now.ToString("dd-MM-yyyy"); 
       int burned = 0; 
       string s = (comboBox1.SelectedItem).ToString(); 
       cnn.Open(); 
       string cmdText = @"SELECT calorificValue 
         FROM myfitsecret.food 
         WHERE [email protected]; 
         SELECT daily_gained 
         FROM myfitsecret.calorie_tracker 
         WHERE [email protected]_id"; 
       using (MySqlCommand cmd = new MySqlCommand(cmdText, cnn)) 
       { 
        // Add both parameters to the same command 
        cmd.Parameters.Add("@name", MySqlDbType.String).Value = s; 
        cmd.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID; 
        using (MySqlDataReader reader = cmd.ExecuteReader()) 
        { 
         // get sum from the first result 
         if (reader.Read()) burned += (Convert.ToInt32(reader[0])*int.Parse(textBox1.Text)); 

         // if there is a second resultset, go there 
         if (reader.NextResult()) 
          if (reader.Read()) 
           burned += Convert.ToInt32(reader[0]); 

        } 

        cmd.Connection.Close(); 

        MySqlCommand cmd2 = new MySqlCommand("update myfitsecret.calorie_tracker set [email protected]_gained where [email protected]_id and [email protected]"); 
        cmd2.CommandType = CommandType.Text; 
        cmd2.Connection.Open(); 
        cmd2.Parameters.AddWithValue("@daily_gained", burned); 
        cmd2.Parameters.AddWithValue("@Date", time); 
        cmd2.Parameters.Add("@sportsman_id", MySqlDbType.String).Value = Login.userID; 
        cmd2.ExecuteNonQuery(); 

答えて

1

あなたはこのようにそれを開こうとする前にされたMySqlCommandへの接続を渡す必要があります:

cmd.Connection.Close(); 

MySqlCommand cmd2 = new MySqlCommand("update myfitsecret.calorie_tracker set [email protected]_gained where [email protected]_id and [email protected]",cnn); 
cmd2.CommandType = CommandType.Text; 
cmd2.Connection.Open(); 

私も同様using声明の中で次のコマンドをラップ助言します。

+0

また、クエリのパラメータを使用することをお勧めします。 – Sybren

関連する問題