How do I know if a request was successful?
How do I know if the next request succeeded INSERT
?
MySqlConnection connection = new MySqlConnection(ConnectionString);
connection.Open();
MySqlCommand command = new MySqlCommand("INSERT INTO People (PersonName, dateAdded) VALUES (?name, NOW())", connection);
command.Parameters.Add(new MySqlParameter("name", Name));
MySqlDataReader Reader = command.ExecuteReader();
I tried to run Reader.Read()
, but only an empty string is returned. Thank.
source to share
Instead, you use ExecuteNonQuery
:
int affectedRows = command.ExecuteNonQuery();
if (affectedRows <= 0)
{
// Houston, we have a problem.
}
Keep in mind, if you have data triggers, this may not reflect the actual number of rows you were trying to execute INSERT
:
You can use
ExecuteNonQuery
to perform any database operation, however any returned results will not be available. Any output parameters used when calling the stored procedure will be populated with data and can be restored after execution completes. ForUPDATE
,INSERT
and statements , theDELETE
return value is the number of rows affected by the command. For all other operator types, the return value-1
.
In general, you will get MySqlException
if your request meets an error.
source to share
Only use the SqlDataReader when you are querying the database, the SqlDataReader is a forward-only fast pointer, so it is recommended only for Querying to use the ExecuteNonQuery () method for the SqlCommand, for example, like the following code:
using (SqlConnection conn = new SqlConnection("[QueryString]")) {
using (SqlCommand cmd = new SqlCommand("SQL Command",conn)) {
//here you return the number of affected rows
int a = cmd.ExecuteNonQuery();
}
}
Hope this can help you.
source to share