Check if a record exists in the database
Asked Answered
S

13

19

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
Sierra answered 23/1, 2014 at 7:46 Comment(3)
What exactly is not an object?Furor
when wil this error display if the user name in table or not?Exploitation
@NicklasWinger Its giving me error on this line, {int UserExist = (int)check_User_Name.ExecuteScalar();}Sierra
L
25

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.
}
Lyricist answered 23/1, 2014 at 7:47 Comment(3)
From database point of view you should use: SELECT top 1 1 FROM [Table] WHERE ([user] = @user) and check if ExecuteScalar is null or not. It performs better than count(*)Gonad
Be careful when using AddWithValue: web.archive.org/web/20210412195621/http://blogs.msmvps.com/… .Mucor
hasRows is a much better option because in your scenario you count on first field value and you should never rely on that, rather has rows will tell you of data was returned or notKnp
B
7

The ExecuteScalar method should be used when you are really sure your query returns only one value like below:

SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'

If you want the whole row then the below code should more appropriate.

SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = @user)" , conn);
check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
   //User Exists
}
else
{
   //User NOT Exists
}
Barbule answered 23/1, 2014 at 8:1 Comment(2)
This won't work because you didn't even add parameter in SqlCommand.Ciel
using ExecuteScalar() is the shortest way.Gloam
P
3
sqlConnection.Open();
using (var sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "'", sqlConnection))
{

    SqlDataReader reader = sqlCommand.ExecuteReader();
    if (reader.HasRows)
    {
        lblMessage.Text ="Record Already Exists.";

    }
    else
    {
        lblMessage.Text ="Record Not Exists.";
    }

    reader.Close();
    reader.Dispose();
}

sqlConnection.Close();
Prance answered 30/1, 2017 at 10:8 Comment(1)
If you're using COUNT(*) you will always get a row with a number even if it's 0 you should just use *Frijol
H
1
MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
    // Exist
}
else {
    // Add 
}
Hobbs answered 21/1, 2018 at 13:41 Comment(1)
This question is using MSSQL, not MySQL.Alvinia
B
0

I would use the "count" for having always an integer as a result

SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);

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

if (UserExist == 1) //anything different from 1 should be wrong
{
  //Username Exist
}
Bans answered 23/1, 2014 at 8:1 Comment(0)
C
0

try this

 public static bool CheckUserData(string phone, string config)
    {
        string sql = @"SELECT * FROM AspNetUsers WHERE PhoneNumber = @PhoneNumber";
        using (SqlConnection conn = new SqlConnection(config)
            )
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                cmd.Parameters.AddWithValue("@PhoneNumber", phone);
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                if (reader.HasRows)
                {
                    return true;  // data exist
                }
                else
                {
                    return false; //data not exist
                }
            }
        }
    }
Chili answered 27/4, 2017 at 9:46 Comment(1)
What does this do? How does it answer OP's question? How is it different from the existing answers? Good answers explain themselves.Alvinia
E
-1

Use try catch:

try
{
    SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);

    int UserExist = (int)check_User_Name.ExecuteScalar();
    // Update query
}
catch
{
    // Insert query
}
Exploitation answered 23/1, 2014 at 7:57 Comment(0)
S
-1

You can write as follows:

SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
    int UserExist = (int)check_User_Name.ExecuteScalar();
    if (UserExist > 0)
    {
        //Username Exist
    }
}
Spillway answered 23/1, 2014 at 8:5 Comment(2)
What if the first column of the first row is not username? You are just guess it is. ExecuteNonQuery is a better approach in this case IMO..Ciel
Yes. you are absolutely right @SonerGönül but with his implemented code, i have given this solution.Spillway
L
-1

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.

Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
  Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault()
  If e Is Nothing Then
    employees.Insert(newE)
  End If
Next  

2.1 seconds

Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
  Try
    employees.Insert(newE)
  Catch ex As Exception
  End Try
Next  

3.1 seconds

Longterm answered 29/4, 2016 at 8:16 Comment(1)
This may answer another question, but it does not answer the question asked above, which is how to do this in ASP.NET WinForms with a SqlCommand.Alvinia
K
-1
sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM  tblAttendance",con);
sda.Fill(dt);

string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);

if (bar >= 1){

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "empty");
}
Keyboard answered 24/9, 2016 at 16:35 Comment(0)
K
-1
protected void btnsubmit_Click(object sender, EventArgs e)
{

        string s = @"SELECT * FROM tbl1 WHERE CodNo = @CodNo";
    SqlCommand cmd1 = new SqlCommand(s, con);
    cmd1.Parameters.AddWithValue("@CodNo", txtid.Text);
    con.Open();
    int records = (int)cmd1.ExecuteScalar();

    if (records > 0)
    {

        Response.Write("<script>alert('Record not Exist')</script>");

    }
    else
    {
        Response.Write("<script>alert('Record Exist')</script>"); 
     }
  }
        private void  insert_data()
{

        SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(@CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',@image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',@NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);

        flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
        string img = @"~/File/" + flpimage.FileName;
        flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
        string img1 = @"~/Tazkiera/" + flpnidcard.FileName;

        comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
        comm.Parameters.AddWithValue("image", flpimage.FileName);
        comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);

        comm.ExecuteNonQuery();
        con.Close();

        Response.Redirect("~/SecondPage.aspx");
        //Response.Write("<script>alert('Record Inserted')</script>");

        }
    }
Kurtzman answered 16/5, 2017 at 5:22 Comment(0)
C
-2

Use the method Int.Parse() instead. It will work.

Coagulant answered 23/1, 2014 at 7:55 Comment(2)
How is that could be useful for OP?Ciel
I tried it and it seems as the object is not really null but rather has some akward casting issue. The parsing worksCoagulant
S
-2

I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.

 var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
  if (result == null) {
      register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
  } else {
      MessageBox.Show("User Alreay Exist. Try with Different Username");
  }
Sickert answered 25/4, 2020 at 4:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.