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";
                }
            }


        }
Carlos Oliveira
  • 477
  • 6
  • 11
  • 1
    What error are you getting? – Karthik Ganesan Jul 02 '14 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? – Steve Jul 02 '14 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. – Tripp Kinetics Jul 02 '14 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? – mclaassen Jul 02 '14 at 19:44

1 Answers1

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);
    }
}
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • thanks a lot i didnt know this is the idea of the `cmd.parameters.addwithvalue ` query now i realized it – Arch_interpreter Jul 02 '14 at 19:50
  • btw id like to know how to check if a record exists for example if ID exists as an already created row – Arch_interpreter Jul 02 '14 at 20:36
  • 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 – Steve Jul 02 '14 at 20:44
  • 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 – Arch_interpreter Jul 02 '14 at 20:59
  • 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. – Steve Jul 02 '14 at 21:09
  • btw what is the `cmd.ExecuteScalar())` returning as long as ineed to convert it to integer but what is it actually – Arch_interpreter Jul 02 '14 at 21:50