string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jettp\Downloads\MockTest\MockTest\Database1.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, Weight FROM MyWeight where Name ='" + txt_Name.Text + "'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (txt_Name.Text != null)
{
sdr.Read();
MessageBox.Show("Username is found");
txt_Name.Text = sdr["Name"].ToString();
txt_Weight.Text = sdr["Weight"].ToString();
con.Close();
}
else
{
lbl_WarningMsg.Text = "Name not found";
con.Close();
}
}
}
}
我试着用这个命令来搜索用户名,它是在找不到数据库,但数据库消息一直说,该名称是在数据库中找到的.这是我得到的错误:
系统操作无效异常:'没有数据时读取尝试无效'
1条答案
按热度按时间kdfy810k1#
因为
if
条件始终为真,所以您将得到Username is found
。请将if
条件更改为: