I have a slight issue in my C# code in Asp.net when deleting a row from sql server. I am using ExecuteNonQuery to determine which message I render to the page. If ExecuteNonQuery returns a 1 then I display success message. Where I am becoming stuck is I have the same logic for adding a record and updating a record and my code works fine. See below for the code.
private void Delete_row(string ImageId)
{
string sSQL = "delete FROM dbo.Image_library_UK_temp where Image_id=" + ImageId;
using (SqlConnection dbConnection = new SqlConnection(app_settings.sql_conn_string_db))
{
try
{
//delete the row from db
dbConnection.Open();
SqlCommand command = new SqlCommand(sSQL, dbConnection);
command.CommandType = CommandType.Text;
command.CommandTimeout = 1024;
command.ExecuteNonQuery();
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected == 1)
{
messagepanel1.ShowSuccessMessage("The image " + txtImgTitle.Text + "has been deleted from the system.");
DisableValidation();
}
}
catch (Exception ex)
{
messagepanel1.ShowErrorMessage("Error: Deletion unsuccessful");
}
Session.RemoveAll();
generateTable(false);
}
}
Rows affected currently returns 0. This is a simple SQL statement so my sql is hard-coded in C# and I am not using a stored procedure.
Any ideas how I can make this work?
Execute the command with the ExecuteNonQuery method of the Command object. The ExecuteNonQuery method returns an integer that represents the number of rows affected by the statement or stored procedure that was executed.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.
ExecuteNonQurey will return an integer ExecuteScala will return an Object. ExecuteReader will return the DataReader object. ExecuteNonQuery() : Doesn't return any data but returns affected row count. Return type is integer.
ExecuteReader method is used to execute a SQL Command or storedprocedure returns a set of rows from the database. Example: public class Sample.
You're executing the command twice.
command.ExecuteNonQuery();
int rowsAffected = command.ExecuteNonQuery();
The first line will delete the row and return 1, but you're ignoring the return value.
The second line will execute the DELETE
statement again, but it won't delete anything, because there is no more rows satisfying the given condition; thus, rowsAffected
will be zero.
Also, your code is vulnerable to sql injections, as was already mentioned in comments. Consider using prepared statements instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With