如何在pd.read_sql_query的查询字符串中使用变量?

发布于 2025-01-29 12:01:25 字数 729 浏览 2 评论 0原文

我正在尝试编写一个运行一些SQL查询的Python脚本。但是,查询该表将在半定期的基础上更改。为了使脚本更加用户友好,我想将表名称存储在变量中。

到目前为止,我拥有的代码看起来像这样:

import pandas as pd

V_pct = "UACO_PCT0000003221"

V_contact_df = pd.read_sql_query(
sql = """"
SELECT DATE(CONTACTDATETIME) AS CONTACT_DATE
FROM AF.{V_pct}
GROUP BY DATE(CONTACTDATETIME);
""",
con = V_conn)

v_conn是我与我要查询的数据库的连接;我遗漏了将其设置为易于阅读的代码。 AF是表格中的模式的名称。数据库为DB2。

当我运行上面的代码时,我会收到此错误:

Exception: Statement Execute Failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0010N  The string constant beginning with ""     SELECT DATE(CONTACTDATETIME) AS CONTACT_DATE     FROM AF.{V_pct}" does not have an ending string delimit SQLCODE=-10E=42603

有人知道我要在哪里做错了吗?

I'm trying to write a python script that runs a few SQL queries. However, the table being queried will change on a semi-regular basis. To make the script more user-friendly I want to store the table name in a variable.

The code I have so far looks like this:

import pandas as pd

V_pct = "UACO_PCT0000003221"

V_contact_df = pd.read_sql_query(
sql = """"
SELECT DATE(CONTACTDATETIME) AS CONTACT_DATE
FROM AF.{V_pct}
GROUP BY DATE(CONTACTDATETIME);
""",
con = V_conn)

V_conn is my connection to the database I'm querying; I've left out the code that sets this up to make things easier to read. AF is the name of the schema the table sits in. The database is DB2.

When I run the code above I get this error:

Exception: Statement Execute Failed: [IBM][CLI Driver][DB2/LINUXX8664] SQL0010N  The string constant beginning with ""     SELECT DATE(CONTACTDATETIME) AS CONTACT_DATE     FROM AF.{V_pct}" does not have an ending string delimit SQLCODE=-10E=42603

Does anyone know where I'm going wrong please?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文