gpt4 book ai didi

python - 在查询中使用 pandas 和命名参数从 mysql 表中读取

转载 作者:行者123 更新时间:2023-11-28 22:26:21 24 4
gpt4 key购买 nike

我尝试执行以下查询

SELECT user_id, user_agent_id, requests 
FROM riskanalysis_user_http_ua_stats
WHERE since>= :since AND until< :until'

我尝试以下 Pandas 代码

sql = 'SELECT user_id, user_agent_id, requests ' \
'FROM riskanalysis_user_http_ua_stats ' \
'WHERE since>= :since AND until< :until'

dataframe_records = pd.read_sql_query(sql, engine,
params={'since':datetime_object,
'until':datetime_object}

我得到以下错误

sqlalchemy.exc.ArgumentError: Could not parse rfc1738 URL from string 'SELECT user_id, user_agent_id, requests FROM riskanalysis_user_http_ua_stats WHERE since>= :since AND until< :until'

我正在使用 pymysql 作为驱动程序和 MySQL 数据库。如何在 sql 查询中传递命名参数?

编辑 1:更正了参数顺序,但现在我得到以下内容

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 ':since AND until< :until' at line 1") [SQL: 'SELECT user_id, user_agent_id, requests FROM riskanalysis_user_http_ua_stats WHERE since>= :since AND until< :until'] [parameters: {'since': datetime.datetime(2015, 6, 18, 0, 0, tzinfo=tzutc()), 'until': datetime.datetime(2015, 6, 18, 0, 2, tzinfo=tzutc())}]

最佳答案

根据 pandas.read_sql_query documentation ,

params : list, tuple or dict, optional, default: None

List of parameters to pass to execute method. The syntax used to pass parameters is database driver dependent. Check your database driver documentation for which of the five syntax styles, described in PEP 249's paramstyle, is supported. Eg. for psycopg2, uses %(name)s so use params={‘name’ : ‘value’}

如果你再看PEP 249's paramstyle ,您会看到很多选项。但是 PyMySQL's execute documentation指出

If args is a list or tuple, %s can be used as a placeholder in the query.

If args is a dict, %(name)s can be used as a placeholder in the query.

因此,适用于您的情况,这将是:

sql = 'SELECT user_id, user_agent_id, requests ' \
'FROM riskanalysis_user_http_ua_stats ' \
'WHERE since>= %s AND until< %s'

dataframe_records = pd.read_sql_query(sql, engine,
params=(datetime_object, datetime_object))

sql = 'SELECT user_id, user_agent_id, requests ' \
'FROM riskanalysis_user_http_ua_stats ' \
'WHERE since>= %(since)s AND until< %(until)s'

dataframe_records = pd.read_sql_query(sql, engine,
params={'since':datetime_object,
'until':datetime_object})

关于python - 在查询中使用 pandas 和命名参数从 mysql 表中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44870107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com