从数据库中获取不符合预期的值

时间:2013-12-18 02:03:53

标签: c# sql

我正在制作一个asp.net应用程序,我正在尝试从sql表中读取数据,但数据不会比较,因为我没有收到消息“你没有银行帐户,你可以注册我们的网站“

SqlConnection connection = new SqlConnection(@"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True");

connection.Open();
SqlDataReader reader = null;
SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber='" + accountnumber1.Text + "'", connection);
reader = command.ExecuteReader();  

if (reader.Read())
{
   string getAccountNumber = reader[0].ToString();
   reader.Close();

   if (getAccountNumber != accountnumber1.Text)
   {
      lblaccountnumber.Visible = true;
      lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
   }
}

2 个答案:

答案 0 :(得分:4)

找到此问题的最佳方法是在该行上设置一个断点:

if (getAccountNumber != accountnumber1.Text)

并查看值不匹配的原因。

我的猜测是,帐号不是SELECT *查询中的第一列,因此reader[0].ToString()不是帐号,而是另一个值。而是通过列名获取列索引,如下所示:

string getAccountNumber = reader.GetString(reader.GetOrdinal("Accountnumber"));

使用参数化查询也是一个好主意,因此您无法访问Little Bobby Tables

以下是使用参数化查询的代码:

string theQuery = "SELECT * FROM ACCOUNTS WHERE Accountnumber=@AccountNumber";

SqlCommand command = new SqlCommand(theQuery, connection);
command.Parameters.AddWithValue("@AccountNumber", accountnumber1.Text);

reader = command.ExecuteReader();

答案 1 :(得分:1)

我会检查reader.HasRows属性并显示消息

using (SqlConnection connection = new SqlConnection(@"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True"))
using(SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber= @Accountnumber", connection))
{
    command.Parameters.AddWithValue("Accountnumber", accountnumber1.Text);
        connection.Open();
    using(SqlDataReader reader = command.ExecuteReader())
    {
        if (!reader.HasRows)
        {
            lblaccountnumber.Visible = true;
            lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
        }
    }

}