如何在pd.read_sql_query的查询字符串中使用变量?
我正在尝试编写一个运行一些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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论