I have been working on trying to check if a record exists in a database table. I have the following code and it is not working.
MySqlConnection connection = new MySqlConnection("My connection string");
string check = string.Format("Select COUNT(*) FROM User_Class WHERE user_class_name = '{0}'", TextBox1.Text);
string query = string.Format("INSERT INTO User_Class (user_class_name) VALUE ('{0}');", TextBox1.Text);
MySqlCommand cmd = new MySqlCommand(check, connection);
MySqlCommand cmd2 = new MySqlCommand(query, connection);
//MySqlDataReader reader;
connection.Open();
if (cmd.BeginExecuteNonQuery().Equals(0))//record does not exist
{
cmd2.BeginExecuteNonQuery();
Label1.Text = "User Class Created!";
Label1.ForeColor = Color.Green;
}
else
{
Label1.Text = "User Class Already Exists";
Label1.ForeColor = Color.Red;
}
This code always goes to the else case. I have also tried doing this using MySqlDataReader but that is also not working. Why is it not returning 0 (or false/null)? What is the best way to check for an empty return?