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.
I want to do:
if (UserExist > 0)
// Update record
else
// Insert record
I was asking myself the same question, and I found no clear answers, so I created a simple test.
I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository.
2.1 seconds
3.1 seconds
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 isnull
, and that's why you getNullReferenceException
when you try to use theExecuteScalar
method.From MSDN;
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 yourSqlConnection
andSqlCommand
:I would use the "count" for having always an integer as a result
Use the method
Int.Parse()
instead. It will work.Use try catch: