asp.net:query有多个条件

时间:2016-12-31 08:51:44

标签: mysql asp.net

1。我有查询。但是无法在条件中添加第二条。请告诉我正确的语义。

2. 如何从下拉列表中获取数据并在gridview中显示。

3. 如果条件满足,我如何从数据库的Tution fee列中获取值,如果条件失败则如何从Hostel Fee获取值。??

protected void BindGridview()
{
    constr = ConfigurationManager.ConnectionStrings["connstring_DETMIS"].ToString(); // connection string
                                                                                  // String FID = DropDownList1.SelectedItem.Value;
    using (var conn = new MySql.Data.MySqlClient.MySqlConnection(constr)) {
        conn.Open();

        using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" + " where F_id =" + DropDownList1.SelectedItem.Value " and C_id=" + DropDownList2.SelectedItem.Value, conn)) {

            using (var reader = cmd.ExecuteReader()) {
                if (reader.HasRows) {
                    gvDetails.DataSource = reader;
                    gvDetails.DataBind();
                } else
                    lblWarning.Text = "There are no records..";
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

欢迎使用 Stackoverflow 。你应该首先研究谷歌为什么你不能添加多个条件(这只是因为简单的语法错误)。

确切的行代码就是这样的。

using (var cmd = new MySql.Data.MySqlClient.MySqlCommand("select * from fees_collect_category" +
                                                      " where F_id = '" + DropDownList1.SelectedItem.Value + "' and C_id=" + DropDownList2.SelectedItem.Value + "'", conn))

注意: - 作为开发人员,我不会建议您通过传递值来执行此操作,因为它很危险且易于SQL INJECTION

我宁愿告诉您使用Parameterized queries

希望有助于和将来使用参数化的,因为它很容易和技术上优先。

答案 1 :(得分:1)

protected void BindGridview()
        {
            String strConnString = ConfigurationManager
                .ConnectionStrings["connstring_DETMIS"].ConnectionString;
            String strQuery = "select * from student_details " +
                               "where F_id=@F_Id and C_id=@C_Id";
            MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(strConnString);

            MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
            cmd.Parameters.AddWithValue("@F_Id",
                DropDownList1.SelectedItem.Value);

            cmd.Parameters.AddWithValue("@C_Id",
                DropDownList2.SelectedItem.Value);

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = strQuery;
            cmd.Connection = con;
            try
            {
                con.Open();
                gvDetails.DataSource = cmd.ExecuteReader();

                gvDetails.DataBind();
            }

            catch (Exception ex)
            {
                throw ex;
            }

        }