【问题标题】:How to reference function argument in a string如何在字符串中引用函数参数
【发布时间】:2016-03-15 17:21:53
【问题描述】:

我有一个函数应该如下查询数据库:

def raw_disc(make):
    data_make = pd.DataFrame(disc.queryRedshift(
    """select D.model_slug,
            D.cap_engine_id,
            D.dealership_id,
            D.cash_percentage,
            D.cash_post_discount_amount as cash_post 
        from quotes_site.discounts D join quotes_site.dealerships DLR 
                on D.dealership_id = DLR.id  
        where DLR.archived <> 't' 
                 and DLR.suspended <> 't', 
                -> and DLR.make = "make"
                 group by 1,2,3,4,5"""))
    return data_make

由于查询位于三引号内,我无法添加包含在参数 make into 子句 where DLR.make = "make" 中的字符串

据我记得在 C 中我会做类似 '%s',$d 的事情(不记得确切)在 python 中是否有类似的方法

任何建议或资源将不胜感激

【问题讨论】:

标签: python sql amazon-redshift


【解决方案1】:

您已标记您的问题 amazon-redshift,并且您的代码显示您使用 Pandas。 Pandas 具有将 SQL 查询(或整个表)的结果读入数据帧的内置功能:

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html

如果您使用与 Redshift 配合使用的 SQLAlchemy,则可以使用 pandas.read_sql 的 params 参数和类似方法:

params : list, tuple or dict, optional, default: None

传递给执行方法的参数列表。用于传递参数的语法取决于数据库驱动程序。检查您的数据库驱动程序文档,了解 PEP 249 的 paramstyle 中描述的五种语法风格中的哪一种受支持。例如。对于 psycopg2,使用 %(name)s 所以使用 params={‘name’ : ‘value’}

示例(假设您安装了 sqlalchemy 和 sqlalchemy-redshift 软件包):

import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('redshift+psycopg2://user:password@xxx.redshift.amazonaws.com:1234/db')

name = 'test'
key = 10

df = pd.read_sql('''SELECT * FROM mytable WHERE name = %(name)s AND key > %(key)s''',
                      engine,
                      params={'name': name, 'key': key})

这避免了SQL injection 的危险,如果您自己走其他人建议的格式化字符串的路线,就会遇到这种危险。

【讨论】:

    【解决方案2】:

    我认为你想要的看起来像这样:

    def raw_disc(make):
        data_make = pd.DataFrame(disc.queryRedshift(
        """select D.model_slug,
                D.cap_engine_id,
                D.dealership_id,
                D.cash_percentage,
                D.cash_post_discount_amount as cash_post 
            from quotes_site.discounts D join quotes_site.dealerships DLR 
                    on D.dealership_id = DLR.id  
            where DLR.archived <> 't' 
                     and DLR.suspended <> 't', 
                    -> and DLR.make = '{0}'
                     group by 1,2,3,4,5""".format(make)))
        return data_make
    

    【讨论】:

      猜你喜欢
      • 2016-06-02
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多