【问题标题】:ASP.Net C# - Setting a MySQL query and parameters based on a conditionASP.Net C# - 根据条件设置 MySQL 查询和参数
【发布时间】:2014-07-30 13:55:06
【问题描述】:

如何根据条件设置 MySQL 查询和参数?

我想要基于“questionSource”的不同查询,如下所示。

但是,在我下面的代码中,'cmd' 在当前上下文中不存在。

或者,我可以为每个条件设置两个不同的函数,并根据需要调用必要的函数,但我想必须有一种方法可以在连接中设置条件。

//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();
    }
}

【问题讨论】:

    标签: c# mysql asp.net parameters ado.net


    【解决方案1】:

    在 if 之前声明 cmd

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

    在if的每一部分

    cmd.CommandText=cmdText;
    

    其他建议:添加

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

    总是在 if 之前,因为它在 if 和 else 部分中以相同的方式使用

    【讨论】:

    • 我在下一行得到“使用未分配的局部变量 'cmd' - 'noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());'
    【解决方案2】:

    您只需将 cmd 的声明移到 if 块之外:

    //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();
        }
    }
    

    【讨论】:

    • 虽然我在下一行得到了“使用未分配的局部变量 'cmd' - 'noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());'
    • 您可以将其初始化为null,如顶部的MySqlCommand cmd = null;,如果在else块之后cmd仍然为null,则提前中止。
    【解决方案3】:

    只需将 MySqlCommand 的声明移到 if/else 块之外,这样您就可以在执行命令的最终尝试中使用它

    //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());
                   ....
              }
        }
    }
    

    还请注意,您应该使用 using 语句来确保您的连接和您的命令已正确关闭和处置。

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 2022-10-08
      • 2021-07-16
      • 2019-06-01
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多