我有一个表在我的数据库和两个文本框和一个按钮在我的ASP.NET。我想调用数据库并选择产品名称和代码,如果入口是正确的,我想要ok消息,否则为false!这是我的代码,但我没有得到正确的结果。
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!";
}
您的查询修改如下
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!";
}
希望这个答案能帮助你解决你的问题。