2012-09-21 19 views
1

我一直有sql語法錯誤..我在這裏錯過了什麼以便在一天中提取數據。從python到mysql的日期時間傳遞值

這裏是我的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 

回答

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參數使用?