gpt4 book ai didi

python - 使用 Python Pandas 将参数传递给 SQL CTE

转载 作者:行者123 更新时间:2023-11-28 18:44:39 29 4
gpt4 key购买 nike

我正在使用 pandas.io.sql 执行一个包含 CTE 的 SQL 脚本,我想做这样的事情:

import pandas.io.sql as psql
param1 = 'park'
param2 = 'zoo'

sqlstr = ("""WITH CTE_A AS (
SELECT *
FROM A
WHERE A.Location = param1),
CTE_B AS (
SELECT *
FROM B
WHERE B.Location = param2)
SELECT A.*, B.*
FROM C
INNER JOIN A
ON C.something = A.something
INNER JOIN B
ON C.something = B.something
WHERE C.combined = param1 || param2
)

我想做这样的事情

    result = psql.frame_query(sqlstr, con = db, params = (param1,param2))

谁能帮我用 Pandas 传递这两个参数?

最佳答案

我知道如何做这样的事情的唯一方法是做下面的事情。但是,它没有利用 Pandas 中的 psql 包。

import pyodbc
import pandas

conn = pyodbc.connect('yourconnectionstring')
curs = conn.cursor()

param1 = 'park'
param2 = 'zoo'

sqlstr = """WITH CTE_A AS (
SELECT *
FROM A
WHERE A.Location = param1),
CTE_B AS (
SELECT *
FROM B
WHERE B.Location = param2)
SELECT A.*, B.*
FROM C
INNER JOIN A
ON C.something = A.something
INNER JOIN B
ON C.something = B.something
WHERE C.combined = ?|| ?;"""
q = curs.execute(sqlstr,[param1,param2]).fetchall()
df = pandas.DataFrame(q)

curs.close()
conn.close()

这会传递参数以避免 SQL 注入(inject),并以包含您的结果的 DataFrame 对象结束

关于python - 使用 Python Pandas 将参数传递给 SQL CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21939691/

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