检查数据库中是否存在记录 [英] Check if a record exists in the database
问题描述
我正在使用这些代码行来检查记录是否存在。
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]
。
作为最后的建议,请使用< a href = http://msdn.microsoft.com/en-us/library/yh598w02.aspx rel = noreferrer> 使用
语句处置 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.
}
这篇关于检查数据库中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!