user2800704
user2800704

Reputation: 57

SQL code for delete Row?

please anyone to explain me what is the problem with following code why didn't delete Table Row.

con.Open();
SqlCommand cmd = new SqlCommand("delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )", con);
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
    Message = "succsess";
}
else
{
    Message = "!";
}
con.Close();

Upvotes: 2

Views: 2126

Answers (4)

pkuderov
pkuderov

Reputation: 3551

Change row with sql command creation to this:

/* look at this - no need to wrap string values with 
   apostrophes since you use parameters */
string query = "delete from RentTable where CID = @id and MID = @mid";

/* create command */
SqlCommand cmd = new SqlCommand(query);

/* set parameters */
cmd.Parameters.AddWithValue("@id", ID);
cmd.Parameters.AddWithValue("@mid", MID);

This's not only solve your problem. This'll help you to prevent problems like it in the future if you'll be using parameters instead concatenation.

PS. Also you have "succsess" misspelled if english word was meant ;)

Upvotes: 2

user2798568
user2798568

Reputation: 31

your command is:

SqlCommand cmd = new SqlCommand(
    "delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' )",
    con
);

while it should be:

SqlCommand cmd = new SqlCommand(
    "delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "' ", 
    con
);

(you should remove the ")" from your command)

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881153

75% of all these types of problems would be fixed if people loaded their queries into a string variable first then printed them out for debugging purposes :-)

You have a closing parenthesis ) at the end of your query which shouldn't be there.

Upvotes: 3

Nathan Koop
Nathan Koop

Reputation: 25197

your sql appears to have a closing brace in it without having an opening brace.

change it to

SqlCommand cmd = new SqlCommand(
     "delete from RentTable where CID = '" + ID + "' and MID = '" + MID + "'"
     , con);

Upvotes: 2

Related Questions