C# 继续接收无效的列名';用户名';

C# 继续接收无效的列名';用户名';,c#,sql,sql-server,C#,Sql,Sql Server,我的数据库中有确切的名字,但我仍然不断地得到这个错误的标题 System.Data.dll中发生“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理 图像链接: 其他信息:列名“Username”无效 protected void Button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(Configura

我的数据库中有确切的名字,但我仍然不断地得到这个错误的标题

System.Data.dll中发生“System.Data.SqlClient.SqlException”类型的异常,但未在用户代码中处理

图像链接:

其他信息:列名“Username”无效

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ERegistrationConnectionString"].ConnectionString);
        conn.Open();

        string checkuser = "select count(*)from Employer where Username='" + TextBoxELUsername.Text + "'";
        SqlCommand com = new SqlCommand(checkuser, conn);
        int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
        conn.Close();
        if (temp == 1)
        {
            conn.Open();
            string checkPasswordQuery = "select password from Employer where Username='" + TextBoxELUsername.Text + "'";
            SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
            string password = passComm.ExecuteScalar().ToString().Replace(" ","");
            if (password == TextBoxLoginPassword.Text)
            {
                Session["New"] = TextBoxELUsername.Text;
                Response.Write("Password is Correct");

            }
            else
            {
                Response.Write("Password Incorrect");

            }
        }
        else
        {
            Response.Write("Username Incorrect");

        }

    }

您的SQL无效。您忘记了
计数(*)
from
关键字之间的空格。请尝试以下方法:

select count(*) from Employer where Username=

此外,您应该将sql更改为不允许sql注入,并在sql语句中使用
参数
对象来检索计数(*)。您确实应该对该语句进行参数化,以防止sql注入

string checkuser = @"select count(*)from Employer where Username= ?";
SqlCommand com = new SqlCommand(checkuser, conn);
comm.Parameters.AddWithValue("?", TextBoxELUsername.Text );
此外,尝试以这种方式返回变量temp

int temp = (int)comm.ExecuteScalar();
除此之外,我将尝试创建包含在IF语句中的第二个连接。这听起来可能有点奇怪,但在IF语句被触发之前,连接可能会被从内存中剥离出来,而程序也不知道您要打开的连接是什么

通过创建一条sql语句,可以避免二次连接

string checkuser = @"select count(*)from Employer where Username= ? and password = ?";
SqlCommand com = new SqlCommand(checkuser, conn);
comm.Parameters.AddWithValue("?", TextBoxELUsername.Text );
comm.Parameters.AddWithValue("?", TextBoxLoginPassword.Text );
只有用户名和密码都正确,您的计数返回才会存在

您可能还希望使用以下代码强制查询区分大小写

alter database your_database collate Latin1_General_CS_AS

该列存在吗?不要以纯文本形式存储密码。始终使用参数以避免sql注入。此代码在糟糕的安全实践中是一个主类。除了明文密码之外,错误消息
密码不正确
告诉我我猜到了一个有效的用户名。根据,您的列名为
EUsername
。您确定连接到了正确的数据库吗?请阅读其他评论,坦率地说,这段代码是一团乱麻。谢谢大家,学习并纠正我的许多错误,也认识到除了这个错误之外的很多事情。谢谢大家,老实说,我在做这个作业时完全模糊了,只需遵循这个视频教程,youtube.com/watch?v=QoPABrUknsE,我的课程只教sql,从不教web开发,我是为了完成作业而被迫这么做的,所以我只是按照上面的教程慢慢理解你们的意思。你们应该检查并停止使用
.AddWithValue()
-这可能会导致意想不到的结果。。。