首页 > 解决方案 > 如何使用 SQL 在 ASP.NET 中选择值

问题描述

我的数据库中有一个表,我的 ASP.NET 中有两个文本框和一个按钮。我要调用数据库并选择产品名称和代码,如果输入正确我要确定消息,否则为错误!这是我的代码,但我没有得到正确的结果。

try
{
    string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
    SqlConnection scon = new SqlConnection(constring);
    scon.Open();
    SqlCommand cmd = new SqlCommand("select * from Product where Name=@Name and Code=@Code", scon);
    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@Code", txtCode.Text);
    SqlDataReader dr = cmd.ExecuteReader();
    scon.Close();
    Label1.Text = "The Product is in our list.Thank you";
}
catch(Exception)
{
    Label1.Text = "The Product is not in our list.Sorry!";
}

标签: asp.netsql-server

解决方案


您的查询修改如下

try
{
    string constring = System.Configuration.ConfigurationManager.ConnectionStrings["WebDataBaseConnectionString"].ConnectionString;
    SqlConnection scon = new SqlConnection(constring);
    scon.Open();
    SqlCommand cmd = new SqlCommand("select * from Product where Name=@Name and Code=@Code", scon);
    cmd.Parameters.Add("@Name", SqlDbType.Varchar).Value = txtName.Text;--Update the datatype as per your table
    cmd.Parameters.Add("@Code", SqlDbType.Varchar).Value = txtCode.Text;--Update the datatype as per your table
    SqlDataReader dr = cmd.ExecuteReader();
    if (dr.HasRows)
    {
        --If you want to check the whether your query has returned something or not then below statement should be ommitted. Else you can check for a specific value while reader is reading from the dataset.
        while (dr.Read())
        {
            --The returned data may be an enumerable list or if you are checking for the rows the read statement may be ommitted.
            --To get the data from the reader you can specify the column name.
            --for example
            --Label1.Text=dr["somecolumnname"].ToString();
            Label1.Text = "The Product is in our list.Thank you";
        }
    }
    else
    {
        Label1.Text = "The Product is not in our list.Sorry!";
    }
    scon.Close();
}
catch (Exception)
{
    Label1.Text = "The Product is not in our list.Sorry!";
}

希望这个答案能帮助您解决您的问题。


推荐阅读