DatabaseError:要执行的第一个参数必须是 python 中的字符串或 unicode 查询

kee*_*mar 2 html sql-server flask python-2.7 pandas

我试图将从日期选择器中选择的日期返回到我的 python 代码中的 sql 查询中。我也尝试使用encode(utf-8)删除 unicode 字符串,但仍然收到错误。

我是Python新手。谁能帮我弄清楚如何解决这个问题吗?我正在使用 python Flask 来创建网页

if request.method=='POST':
        dateval2 = request.form['datepick']
        dateval = dateval2.encode('utf-8')
    result = ("SELECT * FROM OE_TAT where convert(date,Time_IST)='?'",dateval
    df = pd.read_sql_query(result,connection)`
Run Code Online (Sandbox Code Playgroud)

错误

pandas.io.sql.DatabaseError
DatabaseError: Execution failed on sql '("SELECT * FROM OE_TAT where convert(date,Time_IST)='?'", '2015-06-01')': The first argument to execute must be a string or unicode query.
Run Code Online (Sandbox Code Playgroud)

jor*_*ris 6

您向 提供一个元组read_sql_query,而第一个参数(查询)必须是字符串。这就是为什么它给出错误“要执行的第一个参数必须是字符串或 unicode 查询”。

您可以像这样传递参数:

result = "SELECT * FROM OE_TAT where convert(date,Time_IST)=?"
df = pd.read_sql_query(result, connection, params=(dateval,))
Run Code Online (Sandbox Code Playgroud)

请注意, 的使用?取决于您所使用的驱动程序(有不同的方法来指定参数,请参阅https://www.python.org/dev/peps/pep-0249/#paramstyle)。您可能必须使用%s而不是?.

您也可以预先格式化字符串,例如result = "SELECT * FROM OE_TAT where convert(date,Time_IST)={0}".format(dateval),但是,不建议这样做,请参见例如此处