0

How do I go about setting a MySQL query and parameters based on a condition?

I want different queries based on 'questionSource' as shown below.

However, in my code below, 'cmd' does not exist in the current context.

Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.

//validation checks
else
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);

    string questionSource = Session["QuestionSource"].ToString();
    string cmdText = "";

    if (questionSource.Equals("S"))
    {
        cmdText += @"SELECT COUNT(*) FROM questions Q
                    JOIN users U
                    ON Q.author_id=U.user_id
                    WHERE approved='Y'
                    AND role=1
                    AND module_id=@ModuleID";

        MySqlCommand cmd = new MySqlCommand(cmdText, conn);
        cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
        cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
    }
    else if (questionSource.Equals("U"))
    {
        cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=@ModuleID AND author_id=@AuthorID;";

        MySqlCommand cmd = new MySqlCommand(cmdText, conn);
        cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
        cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
        cmd.Parameters.Add("@AuthorID", MySqlDbType.Int32);
        cmd.Parameters["@AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
    }

    int noOfQuestionsAvailable = 0;
    int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);

    try
    {
        conn.Open();

        noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());

        if (noOfQuestionsAvailable < noOfQuestionsWanted)
        {
            lblError.Text = "There are not enough questions available to create a test.";
        }
        else
        {
            Session["TestName"] = txtName.Text;
            Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
            Session["QuestionSource"] = rblQuestionSource.SelectedValue;
            Session["TestModuleID"] = ddlModules.SelectedValue;
            Response.Redirect("~/create_test_b.aspx");
        }
    }
    catch
    {
        lblError.Text = "Database connection error - failed to get module details.";
    }
    finally
    {
        conn.Close();
    }
}

3 Answers 3

1

declare cmd before if

MySqlCommand cmd = new MySqlCommand("",connStr);

and in each part of if

cmd.CommandText=cmdText;

other suggestion: add

cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);

always before if because it is used in the same way in if and else part

Sign up to request clarification or add additional context in comments.

1 Comment

I get 'use of unassigned local variable 'cmd' on the following line - 'noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());'
0

You just have to move the declaration of the cmd outside the if block:

//validation checks
else
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    MySqlConnection conn = new MySqlConnection(connStr);

    string questionSource = Session["QuestionSource"].ToString();
    string cmdText = "";

    MySqlCommand cmd; // <-- here
    if (questionSource.Equals("S"))
    {
        cmdText += @"SELECT COUNT(*) FROM questions Q
                    JOIN users U
                    ON Q.author_id=U.user_id
                    WHERE approved='Y'
                    AND role=1
                    AND module_id=@ModuleID";

        cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand  here
        cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
        cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
    }
    else if (questionSource.Equals("U"))
    {
        cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=@ModuleID AND author_id=@AuthorID;";

        cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand  here
        cmd.Parameters.Add("@ModuleID", MySqlDbType.Int32);
        cmd.Parameters["@ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
        cmd.Parameters.Add("@AuthorID", MySqlDbType.Int32);
        cmd.Parameters["@AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
    }

    int noOfQuestionsAvailable = 0;
    int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);

    try
    {
        conn.Open();

        noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());

        if (noOfQuestionsAvailable < noOfQuestionsWanted)
        {
            lblError.Text = "There are not enough questions available to create a test.";
        }
        else
        {
            Session["TestName"] = txtName.Text;
            Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
            Session["QuestionSource"] = rblQuestionSource.SelectedValue;
            Session["TestModuleID"] = ddlModules.SelectedValue;
            Response.Redirect("~/create_test_b.aspx");
        }
    }
    catch
    {
        lblError.Text = "Database connection error - failed to get module details.";
    }
    finally
    {
        conn.Close();
    }
}

2 Comments

Done though I get 'use of unassigned local variable 'cmd' on the following line - 'noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());'
You can initialize it to null, like MySqlCommand cmd = null; at the top and abort early if cmd is still null after the else block.
0

Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command

//validation checks
else
{
    string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
    using(MySqlConnection conn = new MySqlConnection(connStr))
    using(MySqlCommand cmd = conn.CreateCommand())
    {
         // Don't need to associate the command to the connection
         // Already done by the CreateCommand above, just need to set
         // the parameters and the command text

         if (questionSource.Equals("S"))
         {
                cmdText = @"....."
                cmd.CommandText = cmdText;
                ....
         }
         else if (questionSource.Equals("U"))
         {
                cmdText = "........."
                cmd.CommandText = cmdText;
                ....
         } 
         try
         {
              conn.Open();
              noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
               ....
          }
    }
}

Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.