Python SQL数据库查询给出"参数太少"错误

时间:2015-02-18 18:55:07

标签: python sql ms-access

我有以下代码试图从Access数据库中提取几个SQL查询

import pyodbc
import datetime

conx = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Users\\Stuart\\PycharmProjects\\untitled\\Databases\\SandP.accdb;")

cursor=conx.cursor()

query=""" SELECT DISTINCT Date_ FROM Closing_prices
     WHERE Date_ >= ? AND Date_ < ?"""

params1 = (datetime.date(2011, 8, 10), datetime.date(2014, 4, 30))
cursor.execute(query, params1)

dates = list()
for date in cursor:
    dates.append(date[0])

for date in dates:
    params2 = date
    cursor = conx.cursor()

    query= '''SELECT Volatility,Last_price FROM Volatility v,Closing_prices c WHERE c.Date_= ? and v.Date_=c.Date_'''
    cursor.execute(query,params2)

    for (vol,price) in cursor:
        volatility=float(vol)
        closing_price=float(price)
    cursor.close()

    cursor = conx.cursor()
    if (date.weekday()==4):
        nextDay=(date + datetime.timedelta(days=3))
    else:
        nextDay=(date + datetime.timedelta(days=1))

    query= '''SELECT Date_,Time_, Close_ FROM Intraday_values WHERE (date = ? and time >= ?) or (date = ? and time <= ?)'''

    params3 = (date,datetime.time(15, 30),nextDay,datetime.time(15, 14))
    cursor.execute(query,params3)

最后一点是抛出以下错误:

Traceback (most recent call last):
File "C:/Users/Stuart/PycharmProjects/untitled/Apache - Copy.py", line 67, in <module>
cursor.execute(query,params3)
pyodbc.Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6. (-3010) (SQLExecDirectW)')

请求正在尝试从表中提取Date_,Time_和Close_项目,以查看传递给请求的日期,因为它会迭代先前创建的日期列表,以及“15:30之后的截止时间”对于“日期”和“在15:14之前”为“日期+ 1”。

首先,当SQL请求中只有4个问号(?)时,为什么会期望6个参数 - 我没有正确地形成这个问题吗?

另外,我对datetime.time的参数创建进行了尝试。这也是错误形成的吗?

我有点超出我的深度!

1 个答案:

答案 0 :(得分:2)

更改查询后工作 到

query= '''SELECT Date_,Time_, Close_
          FROM Intraday_values
          WHERE (Date_ = ? and Time_ >= ?)
                OR (Date_ = ? and Time_ <= ?)'''