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.

+3


source to share


4 answers


Don't use ExecuteReader if you are doing INSERT, UPDATE or DELETE. Use ExecuteNonQuery instead, it will return the number of rows affected.



See http://dev.mysql.com/doc/refman/5.6/en/connector-net-tutorials-intro.html#connector-net-tutorials-sql-command

+4


source


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. For UPDATE

, INSERT

and statements , the DELETE

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.

+9


source


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.

+3


source


An exception will be thrown if not met. The exception object usually contains information about what went wrong (for example, "primary key violation", etc.).

Also, use ExecuteNonQuery

for INSERT, UPDATE, or DELETE. The return value will contain the number of affected rows.

+2


source