检查注册页面上是否存在用户

时间:2014-11-13 10:33:27

标签: c# sql asp.net connection-string registration

我正在尝试检查输入的用户名是否已经在名为name的列中名为Table的数据库表中。如果还没有使用它可以进入表格,我已经检查了插入代码分离,它工作正常。

    protected void Unnamed1_Click(object sender, EventArgs e)
    {
        string name = tbUser.Text;
        string pass = tbPass.Text;


        using (SqlConnection connection = new SqlConnection(conString))
        {
            connection.Open();

            string checkUser = "select Count(*) from dbo.Table where name = '"+name+"'";

            SqlCommand command = new SqlCommand(checkUser, connection);
            int temp = Convert.ToInt32(command.ExecuteScalar().ToString());
            if (temp == 1)
            {
                lblError.Text = "Username Taken";
            }
            else
            {
                command.Connection = connection;
                command.CommandType = System.Data.CommandType.Text;

                command.CommandText = "INSERT INTO [dbo].[Table] VALUES(@name, @pass)";

                command.Parameters.Add("@name", System.Data.SqlDbType.NVarChar, 50).Value = name;
                command.Parameters.Add("@pass", System.Data.SqlDbType.NVarChar, 50).Value = GetMd5Hash(pass);

                int rowsAffected = command.ExecuteNonQuery();
            }
        }
    }

我得到的错误是, System.Data.dll中发生了'System.Data.SqlClient.SqlException'类型的异常,但未在用户代码中处理

其他信息:关键字“表格”附近的语法不正确。

1 个答案:

答案 0 :(得分:0)

此行中出现

错误

string checkUser = "select Count(*) from dbo.Table where name = '"+name+"'";

<强>解决方案:

您需要将表放在[]括号中。

string checkUser = "select Count(*) from [dbo].[Table] where name = '"+name+"'";   

<强>信息:

"Reserved keywords should not be used as object names. Databases upgraded from 
earlier versions of SQL Server may contain identifiers that include words not reserved 
in the earlier version, but that are reserved words for the current version of SQL Server.
You can refer to the object by using delimited identifiers until the name can be 
changed." http://msdn.microsoft.com/en-us/library/ms176027.aspx

    "If your database does contain names that match reserved keywords, you must 
use delimited identifiers when you refer to those objects. For more information, 
see Identifiers (DMX)." http://msdn.microsoft.com/en-us/library/ms132178.aspx