ExecuteScalar http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx返回第一行的第一列。其他列或行将被忽略。看起来你的第一行的第一列是null
,这就是为什么你得到NullReferenceException http://msdn.microsoft.com/en-us/library/system.nullreferenceexception.aspx当你尝试使用ExecuteScalar
method.
From MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx;
返回值
结果集中第一行的第一列,或空值
如果结果集为空则引用.
您可能需要使用COUNT
在您的语句中,而不是返回受影响的行数...
Using 参数化查询 http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html始终是一个很好的做法。它可以防止SQL注入 http://en.wikipedia.org/wiki/SQL_injection攻击。
And Table
is a 保留关键字 http://msdn.microsoft.com/en-us/library/ms189822.aspx在 T-SQL 中。您应该将它与方括号一起使用,例如[Table]
also.
作为最终建议,请使用using陈述 http://msdn.microsoft.com/en-us/library/yh598w02.aspx处置你的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.
}