如何在 MySQL 语句中使用 .format() 字符串?
How to use .format() string in a MySQL statement?
我正在尝试使用今天以及 7 天前的数据来格式化 MySQL 语句。我很确定日期的格式正确,所以我认为这不是问题所在。
报错为:
Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
result = self._query(query)
Traceback (most recent call last):
AttributeError: 'int' object has no attribute 'format'
例如
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))
cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)
使用准备好的语句(安全方式):
qry = """
SELECT *
FROM db
WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" #
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d')) # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string
cursor.execute(qry, [today, week_ago])
使用 .format() 会使您面临 sql 注入的风险(例如,如果您将用户输入传递给 .format())
qry = """
SELECT *
FROM db
WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d')) # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string
qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)
我正在尝试使用今天以及 7 天前的数据来格式化 MySQL 语句。我很确定日期的格式正确,所以我认为这不是问题所在。
报错为:
Warning: (1292, "Incorrect datetime value: '{} 16:00:00' for column 'run_start_date' at row 1")
result = self._query(query)
Traceback (most recent call last):
AttributeError: 'int' object has no attribute 'format'
例如
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
print(today.strftime('%Y-%m-%d'))
print(week_ago.strftime('%Y-%m-%d'))
cursor.execute(SELECT * FROM db WHERE run_start_date BETWEEN '{} 16:00:00' AND '{} 16:00:00'format(week_ago, today)
使用准备好的语句(安全方式):
qry = """
SELECT *
FROM db
WHERE run_start_date BETWEEN '%s 16:00:00' AND '%s 16:00:00'
""" #
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d')) # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string
cursor.execute(qry, [today, week_ago])
使用 .format() 会使您面临 sql 注入的风险(例如,如果您将用户输入传递给 .format())
qry = """
SELECT *
FROM db
WHERE run_start_date BETWEEN '{today} 16:00:00' AND '{week_ago} 16:00:00'
""" # Use named placeholders, nicer to read, prevents you having to repeat variables multiple time when calling .format()
today = DT.date.today()
week_ago = today - DT.timedelta(days=7)
today = str(today.strftime('%Y-%m-%d')) # Convert to string
week_ago = str(week_ago.strftime('%Y-%m-%d')) # Convert to string
qry = qry.format(today=today, week_ago=week_ago)
cursor.execute(qry)