简体   繁体   English

如何使用MySQL,Pandas和SQLAlchemy在proc调用中正确传递参数?

[英]How do you properly pass a parameter in a proc call with MySQL, Pandas and SQLAlchemy?

With Python 2.7, when I use sqlalchemy and pandas to run a proc call from MySQL, I get this error: 使用Python 2.7时,当我使用sqlalchemy和pandas从MySQL运行proc调用时,出现以下错误:

sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError) (1064, u'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 \\'2018-03-10\\'","end_date":"\\'2018-03-16\\'" sqlalchemy.exc.ProgrammingError:(pymysql.err.ProgrammingError)(1064,u'您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册以获取在\\'2018-03-附近使用的正确语法10 \\'“,”结束日期“:” \\'2018-03-16 \\'“

start_date = datetime.date(2018, 3, 10)
end_date = datetime.date(2018, 3, 16)

proc_call = text('''call schema.proc_call('{"start_date"\\:":start_date","end_date"\\:":end_date","foo":"1", "foo2":2}')''')

results = pd.read_sql_query(proc_call, con=connection, params={"start_date": start_date, "end_date": end_date})

It works when the dates are hard coded, but I need them to be parameters. 当日期经过硬编码时可以使用,但是我需要将它们用作参数。

Looks like you are trying to pass a JSON string to proc_call , so do just that. 看起来您正在尝试将JSON字符串传递给proc_call ,所以只需这样做。 Create a suitable Python construct, encode as JSON, and pass it as the argument: 创建一个合适的Python构造,编码为JSON,并将其作为参数传递:

import json

start_date = datetime.date(2018, 3, 10)
end_date = datetime.date(2018, 3, 16)
arg0 = {"start_date": start_date, "end_date": end_date, "foo": "1", "foo2": 2}

proc_call = text('call schema.proc_call(:arg0)')

results = pd.read_sql_query(proc_call, con=connection,
                            params={"arg0": json.dumps(arg0)})

The error is the result of trying to use placeholders inside a string literal. 该错误是尝试在字符串文字内使用占位符的结果。 The end result is something along the lines of 最终的结果是

'{"start_date":"'2018-03-10'", ...}'

which is the string literal '{"start_date":"' followed by 2018-03-10 and so on, which is not valid syntax. 这是字符串文字'{"start_date":"'后跟2018-03-10 ,依此类推,这是无效的语法。


You could also take using bound parameters a step further and specify their type explicitly : 您还可以进一步使用绑定参数,并显式指定其类型

from sqlalchemy import bindparam, JSON

start_date = datetime.date(2018, 3, 10)
end_date = datetime.date(2018, 3, 16)
arg0 = {"start_date": start_date, "end_date": end_date, "foo": "1", "foo2": 2}

proc_call = text('call schema.proc_call(:arg0)')
proc_call = proc_call.bindparams(bindparam('arg0', type_=JSON))

results = pd.read_sql_query(proc_call, con=connection, params={"arg0": arg0})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM