Check if a record exists in the database

前端 未结 13 1760
借酒劲吻你
借酒劲吻你 2020-11-28 12:58

I am using these lines of code to check if the record exists or not.

SqlCommand check_User_Name = new SqlCommand(\"SELECT * FROM Table WHERE ([user] = \'\" +         


        
13条回答
  •  天命终不由人
    2020-11-28 13:16

    ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method.

    From MSDN;

    Return Value

    The first column of the first row in the result set, or a null reference if the result set is empty.

    You might need to use COUNT in your statement instead which returns the number of rows affected...

    Using parameterized queries is always a good practise. It prevents SQL Injection attacks.

    And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also.

    As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand:

    SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = @user)" , conn);
    check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
    int UserExist = (int)check_User_Name.ExecuteScalar();
    
    if(UserExist > 0)
    {
       //Username exist
    }
    else
    {
       //Username doesn't exist.
    }
    

提交回复
热议问题