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] = \'\" +
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
}
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
}
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
}
}
}
}
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
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();
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
}
}