Reputation: 31471
How can I know if the following INSERT
query succeeded?
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 running Reader.Read()
but only an empty string is returned. Thanks.
Upvotes: 3
Views: 6858
Reputation: 96
Only use the SqlDataReader when you're queryng the data base, the SqlDataReader is a fast forward-only pointer, so only is recommended for Querying, use the ExecuteNonQuery() method of the SqlCommand, for example as the next 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();
}
}
Upvotes: 3
Reputation: 64068
You instead use ExecuteNonQuery
:
int affectedRows = command.ExecuteNonQuery();
if (affectedRows <= 0)
{
// Houston, we have a problem.
}
Keep in mind if you have triggers on the data, it may not reflect the actual number of rows you attempted to INSERT
:
You can use
ExecuteNonQuery
to perform any type of database operation, however any resultsets returned will not be available. Any output parameters used in calling a stored procedure will be populated with data and can be retrieved after execution is complete. ForUPDATE
,INSERT
, andDELETE
statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is-1
.
In general, however, you will receive a MySqlException
if your query encounters an error.
Upvotes: 9
Reputation: 52107
An exception will be thrown if it fails. The exception object will typically contain information about what went wrong (e.g. "primary key violation" etc...).
Also, use ExecuteNonQuery
for INSERT, UPDATE or DELETE. The returned value will contain the number of affected rows.
Upvotes: 2
Reputation: 8408
Don't use ExecuteReader if you're doing an INSERT, UPDATE or DELETE. Use ExecuteNonQuery instead, it'll return the number of affected rows.
Upvotes: 4