如何解决编程错误:(1064,“您的SQL语法有错误)?

时间:2019-10-15 09:35:26

标签: python mysql

我正在使用pymysql从MySQL数据库中获取数据,但出现此错误

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '23:59:00' at line 1")

我的代码如下

cursor1 = price_db.cursor()
cursor1.execute('select * from bo_prices.chart_prices where price_date = {};' .format(string_time)) # Extract 'chart_price' table from price db
data7 = cursor1.fetchall()
chart_price = pd.DataFrame(data7)

string_time是

string_time = srt(datetime.datetime.combine(datetime.date(2019,10,07), datetime.time(23,59)))

如何修复它以获取数据?谢谢!

2 个答案:

答案 0 :(得分:5)

您永远不要对SQL查询使用字符串格式。

您应该使用替换。

q = "select * from bo_prices.chart_prices where price_date = '(?)'"
v = (string_time,)
cursor1.execute(q, v) 

实际上是documentation of parameter substitution is quite good.

答案 1 :(得分:1)

不引用日期值,只需将单引号添加到where子句{}

cursor1.execute("select * from bo_prices.chart_prices where price_date = '{}';" .format(string_time))