检查数据库中是否存在记录

检查数据库中是否存在记录

问题描述:

我正在使用这些代码行来检查记录是否存在。

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] = '" + txtBox_UserName.Text + "') ", conn);

int UserExist = (int)check_User_Name.ExecuteScalar();

但是我遇到了一个错误:

But I am getting an error:

Object reference not set to an instance of an object.

我想做的事情:

if (UserExist > 0)
    // Update record

else

    // Insert record


ExecuteScalar 返回第一行的第一列。其他列或行将被忽略。看起来您第一行的第一列是 null ,这就是为什么您得到 ExecuteScalar $ c $时,library / system.nullreferenceexception.aspx rel = noreferrer> NullReferenceException c>方法。

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.

来自 MSDN ;


返回值

Return Value

结果集中第一行的第一列,;如果结果集为空,则返回空的

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

您可能需要在语句中使用 COUNT 来代替返回受影响的行数...

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

使用 参数化查询 一直在一个很好的做法。它可以防止 SQL注入 攻击。

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

保留的关键字 在T-SQL中。您应该将其与方括号一起使用,例如 [Table]

作为最后的建议,请使用 使用语句处置 SqlConnection SqlCommand

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.
}