日期时间从python到mysql的传递值

时间:2012-09-21 18:07:40

标签: python mysql database date

我一直有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  

1 个答案:

答案 0 :(得分:6)

您使用格式化参数执行查询但从未传递这些参数; % (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参数。