Python - 在MySQL语句中使用.format()字符串

时间:2017-11-15 23:11:53

标签: python mysql string.format

我正在尝试使用今天的数据格式化mysql语句,以及7天后。我很确定日期的格式是正确的,所以我认为这不是问题所在。

错误报告是:

 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'

e.g。

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)

1 个答案:

答案 0 :(得分:4)

使用预准备语句(安全方式):

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)