【问题标题】:Read python variable in Oracle-sql query在 Oracle-sql 查询中读取 python 变量
【发布时间】:2020-04-15 09:08:40
【问题描述】:

我想在 python 循环中保留 oracle-sql 查询。所以很少有python变量需要放在sql查询中。以下是我的代码:

import pandas as pd
import cx_Oracle
for i in range(df.shape[0]):
        a=df.iloc[i,0]
        b=df.iloc[i,1]
        c=df.iloc[i,2]
        d=df.iloc[i,3]

        con = cx_Oracle.connect('xyz', encoding='utf-8')

        SQL_query= '''SELECT q1.*,
             CASE
                WHEN start_date BETWEEN {a} AND {b} THEN '14A'
                WHEN start_date BETWEEN {c} AND {d} THEN '14B'..........'''
        pdf1 = pd.read_sql(SQL_query , con)

如您所见,a,b,c,d 放在大括号中。我想将其视为变量,但代码将其视为字符串

【问题讨论】:

  • 另外不要打开/关闭数据库连接循环。

标签: python sql python-3.x oracle oracle11g


【解决方案1】:

切勿将用户数据连接或插入到 SQL 语句中。更喜欢使用绑定变量,这有助于避免 SQL 注入安全问题,因为数据永远不会被视为可执行语句的一部分,通过为每个变量加上 冒号 ( : )作为

SQL_query  = "SELECT q1.*, "
SQL_query += " CASE "
SQL_query += " WHEN start_date BETWEEN to_date(:a,'yyyy-mm-dd') AND to_date(:b,'yyyy-mm-dd') THEN '14A' "
SQL_query += " WHEN start_date BETWEEN to_date(:c,'yyyy-mm-dd') AND to_date(:d,'yyyy-mm-dd') THEN '14B'.........."

pdf1 = pd.read_sql(SQL_query, con, params=['2020-01-01','2020-04-15','2019-01-01','2019-04-15']);

按绑定变量a、b、c的顺序说明params数组中的所有四个变量值strong> 和 d

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 1970-01-01
    • 2016-05-05
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多