Shakya_A
Shakya_A

Reputation: 17

MySQL delete rows in a table using Python

I am using Python3 and MySQL. I have a string value in date and time format (dateS).

  import datetime
  dateS = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
  # print(dateS)                 # 2018-08-27 00:30:00

I need to delete rows in table "bts_l3_single_value_data" checking with the condition where start_time is equal to mentioned datetime.

  sql = """DELETE FROM bts_l3_single_value_data WHERE start_time = dateS"""

When I execute this I'm getting an error as " Error: (1054, "Unknown column 'dateS' in 'where clause'") " and when I print the sql statement it gives as;

 DELETE FROM bts_l3_single_value_data WHERE start_time = dateS 

without converting the dateS string to datetime format.

Any help. Thanks

Upvotes: 0

Views: 577

Answers (2)

Upasana Mittal
Upasana Mittal

Reputation: 2680

use .format for inducing value like this in sql query. Below is an example for that

sql = """
         DELETE FROM from bts_l3_single_value_data where start_time ='{}'
       """.format(dateS)

Upvotes: 0

Đào Minh Hạt
Đào Minh Hạt

Reputation: 2930

You are using dateS as a string, if you want to put parameter there better use f strings

sql = f"""DELETE FROM bts_l3_single_value_data WHERE start_time = {dateS}"""

But it's better to use sql variables for more secured.

Upvotes: 2

Related Questions