纠正连接查询。 C#和MySQL

时间:2013-11-25 20:28:01

标签: c# mysql concatenation

我的数据库中有一个包含4列Specie |的表Price | Stock | Country。 和两个下拉列表,第一个是Country选择国家/地区后第二个下拉列表显示分配给该国家/地区的Specie。 这一切都运作良好。

我有两个下拉列表

  1. ddlcountry,供用户选择国家/地区

  2. DdPetPist是Specie列表

  3. 问题

    我选择了索引更改,其中显示了选中PriceSpecie的2个标签。 问题是标签没有显示所选国家/地区的正确打印,我知道它的查询,但我已经尝试了几种变化,似乎无法让它正常工作,建议或帮助将不胜感激。

    以下查询的代码

     protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selection_price = DdPetPist.SelectedValue;
            string selection_stock = DdPetPist.SelectedValue;
            string petPrice = string.Empty;
            string available = string.Empty;
    
            MySqlCommand cd_price = new MySqlCommand(String.Format("SELECT Price FROM Animals WHERE Specie ='{0}'", ddlcountry.Text, selection_price), cs);
            MySqlCommand cd_available = new MySqlCommand(String.Format("SELECT Stock FROM Animals WHERE Specie ='{1}'", ddlcountry.Text, selection_stock), cs);
    
            cs.Open();
            petPrice = Convert.ToString(cd_price.ExecuteScalar());
            available = Convert.ToString(cd_available.ExecuteScalar());
            cs.Close();
    
            PetPrice.Text = String.Format("Minimum Donation For A {0}  Is £{1}.", selection_price, petPrice);
            Availble.Text = String.Format("{0}'s Avalible {1} In Your Country.", selection_stock, available);
        } 
    

1 个答案:

答案 0 :(得分:0)

MySqlCommand cd_price = new MySqlCommand(String.Format("SELECT Price FROM Animals WHERE Specie ='{0}'", ddlcountry.Text, selection_price), cs);
MySqlCommand cd_available = new MySqlCommand(String.Format("SELECT Stock FROM Animals WHERE Specie ='{1}'", ddlcountry.Text, selection_stock), cs);

如果字符串中只有一个参数,则为查询提供两个参数。您希望Specie列与ddlcountry值匹配...我认为您输入了错误的下拉列表。

您应该使用参数化查询:

MySqlCommand m = new MySqlCommand("SELECT Price FROM Animals WHERE Specie = @specie");
m.Parameters.AddWithValue("@specie", ddlcountry.Text);

Link to documentation