简体   繁体   English

.NET SqlDataReader:用户代码未处理SqlException

[英].NET SqlDataReader: SqlException was unhandled by user code

Working on building a simple .NET web application using a SQL Server table created. 使用创建的SQL Server表来构建简单的.NET Web应用程序。 I continuely get errors in regards to the SqlDataReader, and am stuck on where I'm going wrong. 关于SqlDataReader,我不断收到错误消息,并一直停留在出错的地方。

Here is my error: Additional information: Incorrect syntax near the keyword 'Table'. 这是我的错误:其他信息:关键字“表”附近的语法不正确。

Here is my code: 这是我的代码:

EDIT: 编辑:

            bool authenticated = AuthenticateMe(txtUsername.Text, txtPassword.Text);

        if (authenticated)
        {
            Response.Redirect("Home.aspx");
        }
        else
        {
            Response.Redirect("Default.aspx");
        }
    }

    private bool AuthenticateMe(string username, string password)
    {
        //  string ErrorMessage = "";
        string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";
        string commandText = "SELECT Username from [Table] where Username = @name AND Password = @pwd";
        //   try
        //  {
        using (SqlConnection sqlConnection1 = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand(commandText, sqlConnection1))
        {
            sqlConnection1.Open();
            cmd.Parameters.AddWithValue("@name", username);
            cmd.Parameters.AddWithValue("@pwd", password);
            int result = (int)cmd.ExecuteNonQuery();

            if (result > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }

    }

1st Version (prior to edit): 第一版(修改前):

        protected void bnLogin_Click(object sender, EventArgs e)
    {

        bool authenticated = AuthenticateMe(txtUsername.Text, txtPassword.Text);

        if (authenticated)
        {
            Response.Redirect("Home.aspx");
        }
        else
        {
            Response.Redirect("Default.aspx");
        }
    }

    private bool AuthenticateMe(string userName, string password)
    {

        string connectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;Connect Timeout=30";

        SqlConnection sqlConnection1 = new SqlConnection(connectionString);
        sqlConnection1.Open();

        SqlCommand cmd = new SqlCommand("SELECT Username from Table where Username = userName");

        cmd.Connection = sqlConnection1;

        SqlDataReader reader = cmd.ExecuteReader();
        Response.Write("Entered Sucessfully");

        reader = cmd.ExecuteReader();
        string localUserName = (string)reader["Username"];

        sqlConnection1.Close();


        if (userName.Equals(localUserName))
        {
            return true;
        }

        else
        {
            return false;
        }

Table is a reserved keyword in SQL. 表是SQL中的保留关键字。 Try putting square brackets around it: 尝试在其周围放置方括号:

SqlCommand cmd = new SqlCommand("SELECT Username from [Table] where Username = userName");

Table is a keyword. 表是一个关键字。 If your table is called Table , your sql must escape it. 如果您的表名为Table ,则您的sql必须对其进行转义。 Try [Table] . 尝试[Table]

Note also that you'll want to use a parameter for the username - ie where Username = @userName , where you also add a parameter with that name to the command with the appropriate value. 还要注意,您将要为用户名使用一个参数-即where Username = @userName ,您还需要在该命令中将具有该名称的参数添加到具有适当值的命令。

I think there are 2 issues with your SQL query. 我认为您的SQL查询有2个问题。

" SELECT Username from Table where Username = userName " 从表中选择用户名,其中用户名=用户名

  1. Table is a reserved keyword. 是保留关键字。 Use another name for the table or [Table] . 该表或[Table]使用其他名称。
  2. The last part, Username = username , is also wrong. 最后一部分, Username = username ,也是错误的。 If your intention was to have a constant string there, you should consider putting the username in quotes \\'username\\' . 如果您打算在那里有一个常量字符串,则应考虑将用户名放在引号\\'username \\'中 Don't forget about the escape symbol. 不要忘记逃生符号。 And if you want to pass a parameter to the SQLCommand, use @username in the query and pass the value this way 如果要向SQLCommand传递参数,请在查询中使用@username并以这种方式传递值

    cmd.Parameters["@username"].Value = "Bob"; cmd.Parameters [“ @ username”]。Value =“ Bob”;

Your AuthenticateMe method seems a bit wrong and ineffective to authenticate the user 您的AuthenticateMe方法似乎有点错误,无法验证用户身份

  • You use a reserved keyword (Table) without the proper delimiters (Square brackets) 您使用的保留关键字(表格)没有适当的定界符(方括号)
  • You don't pass the username and the password to the query that checks if the user is present 您不会将用户名和密码传递给检查用户是否存在的查询
  • You call two times the ExecuteReader (?) 您两次调用ExecuteReader(?)
  • You check the returned value from the query with the same value used for the search (useless) 您检查查询返回的值是否与用于搜索的值相同(无用)

So you could rewrite the code in this way 所以你可以这样重写代码

private bool AuthenticateMe(string userName, string password)
{
    string connectionString = @".....";
    string commandText = "SELECT COUNT(*) from [Table] where Username = @name AND Pass = @pwd");
    using(SqlConnection sqlConnection1 = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(commandText, sqlConnection1))
    {
         sqlConnection1.Open();
         cmd.Parameters.AddWithValue("@name", username);
         cmd.Parameters.AddWithValue("@pwd", password);
         int result = Convert.ToInt32(cmd.ExecuteScalar());
         return (result > 0);
    }
}

Also, keep in mind that is considered a bad practice to store the passwords in the database in plain text. 另外,请记住,将密码以纯文本格式存储在数据库中被认为是一种不好的做法。 Some kind of hash function should be applied to the password memorized to forbid any security problem if someone get a copy of the database. 如果有人获得了数据库的副本,应该对记忆的密码应用某种哈希函数,以防止出现任何安全问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM