0

basically this is my inserting function which inserts string into sql table

[System.Web.Services.WebMethod]     
        public static string InsertData(string ID)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();          
            using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("Insert into Book (Name) values(@Name)", con))
                    {
                        con.Open();
                        cmd.Parameters.AddWithValue("@Name", ID);
                        cmd.ExecuteNonQuery();
                        con.Close();
                        return "True";
                    }
                }
        }

Now i want to remove a row from this table if exist and i tried this but i seems to get error when executing the query.

  [System.Web.Services.WebMethod]
        public static string DeleteData(string ID)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand
                    (
                    "Delete from Book Where Name = "+ID.ToString()
                    , con))
                {
                    con.Open();                                     
                    cmd.ExecuteNonQuery();                   
                    con.Close();
                    return "True";
                }
            }


        }
4
  • 1
    What error are you getting? Commented Jul 2, 2014 at 19:43
  • 2
    Can you explain why you ditched the correct way to query a database using a parameterized query and use instead a very wrong string concatenation? Commented Jul 2, 2014 at 19:43
  • As an aside, I would highly recommend not generating SQL queries through string concatenation, because it opens you up for all kinds of SQL injection security problems later. Commented Jul 2, 2014 at 19:43
  • 1
    Missing quotes around value in Where Name = "+ID.ToString() ? Also why not use a parameterized query there also? In fact, why not just use Entity Framework? Commented Jul 2, 2014 at 19:44

1 Answer 1

2

Notice how the ID variable passed to your method is a string?
This means that the Name field used in the WHERE clause is expecting a string to find the row to delete. Strings, when used as values in a Sql WHERE are passed enclosed in single quotes.

For example, if you write your query directly in Sql Server Management Studio:

 DELETE FROM Book WHERE Name = 'xyz'

Without the quotes you get an error and this is probably your problem now.

The solution is just to follow the same steps used when you inserted the new row. A parameterized query and you don't need to worry about quoting your strings or worse about Sql Injections

[System.Web.Services.WebMethod]
public static string DeleteData(string ID)
{
        string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(@"Delete from Book 
                                                     Where Name = @ID" , con))
            {
                con.Open();                                     
                cmd.Parameters.AddWithValue("@ID", ID);
                cmd.ExecuteNonQuery();                   
                con.Close();
                return "True";
            }
        }
  }

The delete operation is safe, because if the record doesn't exist, then the WHERE clause cannot find any row to delete. However, if you need for other purposes a check for the existance or not of a record you could write something like this

public static bool Exists(string ID)
{
    string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
    using (SqlConnection con = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand(@"
                      IF EXISTS(SELECT 1 FROM Book Where Name = @ID)
                      SELECT 1 ELSE SELECT 0" , con))
    {
         con.Open();                                     
         cmd.Parameters.AddWithValue("@ID", ID);
         int result = Convert.ToInt32(cmd.ExecuteScalar()); 
         return (result == 1);
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

thanks a lot i didnt know this is the idea of the cmd.parameters.addwithvalue query now i realized it
btw id like to know how to check if a record exists for example if ID exists as an already created row
Well, the delete operation is safe, because, if the record doesn't exist then no record with the ID specified will be found. If you want to know if a record exists then I will update the answer
so in javascript if i call it like if (PageMethods.Exists(ID) == true){ do something} it will check if ID row exists and then do something if it exists
Well, I am not so confident about javascript to give you an answer with absolute certainty. I think you should post a new question with javascript in the TAGS list to attract people more expert than me in that language.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.