You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jupyter Notebook中使用PostgreSQL SQL脚本变量

在Jupyter Notebook中通过SQLAlchemy使用SQL变量的解决方法

以下是几种可靠的实现方式,帮你避免手动修改SQL脚本:

方法1:使用SQLAlchemy的text()对象+参数绑定(推荐,防SQL注入)

这是最安全的方式,SQLAlchemy会自动处理变量转义和类型匹配:

from sqlalchemy import text
import pandas as pd

# 定义变量
num = 50

# 编写带占位符的SQL脚本,用:变量名标记
script = text('select * from table1 where employees = :num')

# 执行查询时传入参数(假设已创建engine连接对象)
with engine.connect() as conn:
    result = conn.execute(script, {'num': num})
    df = pd.DataFrame(result.fetchall(), columns=result.keys())

# 查看结果
df.head()

方法2:使用f-string格式化(仅适用于可信变量,注意SQL注入风险)

如果变量是你自行定义、无外部输入的安全值,可以直接用Python的f-string拼接SQL:

num = 50

# 用f-string替换变量
script = f'select * from table1 where employees = {num}'

with engine.connect() as conn:
    result = conn.execute(text(script))
    df = pd.DataFrame(result.fetchall(), columns=result.keys())

注意:若变量来自外部用户输入,这种方式可能引发SQL注入,生产环境谨慎使用。

方法3:使用数据库原生占位符(适配不同数据库)

不同数据库的占位符语法略有差异,比如MySQL、PostgreSQL支持%s,SQLite支持?:

num = 50

script = text('select * from table1 where employees = %s')

with engine.connect() as conn:
    # 参数以元组形式传入
    result = conn.execute(script, (num,))
    df = pd.DataFrame(result.fetchall(), columns=result.keys())

你之前的写法错误在于:仅定义了带:num的SQL脚本,但没有将num变量传递给查询执行方法,导致SQLAlchemy无法识别占位符对应的实际值。

内容的提问来源于stack exchange,提问作者Danish Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 04:09:56