继续收到无效的列名称'用户名'

时间:2014-11-12 15:02:10

标签: c# sql sql-server

我在我的数据库中有确切的名称但我仍然继续将该错误标题为。

  

System.Data.dll中出现'System.Data.SqlClient.SqlException'类型的异常,但未在用户代码中处理

图片链接:http://i.imgur.com/tKtvlfj.png

其他信息:无效的列名称“用户名”。

    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");

        }

    }

2 个答案:

答案 0 :(得分:0)

您的SQL无效。您忘记了count(*)from关键字之间的空格。试试这个:

select count(*) from Employer where Username=

此外,您应该将sql更改为不允许sql注入并使用Parameters对象

答案 1 :(得分:0)

在你的Sql语句检索count(*)的情况下,你真的应该参数化该语句以防止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