简体   繁体   中英

Adding and Deleting data from sql database via asp.net

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


        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM