【问题标题】:date time pass value from python to mysql从python到mysql的日期时间传递值
【发布时间】:2012-09-14 04:35:04
【问题描述】:

我一直有 sql 语法错误。为了按天提取数据,我在这里遗漏了什么。

这是我的 python 错误:

pyodbc.ProgrammingError: ('42000', "[42000] [MySQL][ODBC 5.1 Driver][mysqld-5.1.63rel13.4-log]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 '%s and date_created < %s ,(start, next)' at line 11 (1064) (SQLExecDirectW)")
File "d:\sasdev\datax\program\py\global.py", line 33, in <module>
  """)

代码如下:

start = datetime.date(2012,01,01)
next = start + datetime.date.resolution

while next <= datetime.date.today():
     print start, next 

     cur_ca.execute("""
             select id,
         date_created,
         data
         from bureau_inquiry where date_created >= %s and date_created < %s %(start, next)
         """)
     start = next
     next = start + datetime.date.resolution  

【问题讨论】:

    标签: python mysql database date


    【解决方案1】:

    您使用格式化参数执行查询,但从不传递这些参数; % (start, next) 部分位于 SQL 查询的外部

    cur_ca.execute("""
             select id,
         date_created,
         data
         from bureau_inquiry where date_created >= %s and date_created < %s
         """ % (start, next)
       )
    

    不过,最好使用 SQL 参数,这样数据库就可以准备查询并重用查询计划:

    cur_ca.execute("""
             select id,
         date_created,
         data
         from bureau_inquiry where date_created >= ? and date_created < ?
         """, (start, next)
       )
    

    PyODBC 将? 用于 SQL 参数。

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 2011-12-03
      • 2022-01-20
      • 1970-01-01
      • 2014-01-18
      相关资源
      最近更新 更多