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

时间:2015-06-24 06:41:31

标签: html sql-server python-2.7 pandas flask

我试图在我的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)`

错误

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.

1 个答案:

答案 0 :(得分:2)

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

你可以像这样传递参数:

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

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

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

相关问题