繁体   English   中英

多次传递此变量的有效方法

[英]Efficient way to pass this variable multiple times

我在Python中使用Pyodbc来运行一些SQL查询。 我正在使用的实际上比这更长,但这个例子捕获了我正在尝试做的事情:

connection = pyodbc.connect(...)
cursor = connection.cursor(...)

dte = '2018-10-24'

#note the placeholders '{}'
query = """select invoice_id
    into #output 
    from table1 with (nolock) 
    where system_id = 'PrimaryColor' 
    and posting_date = '{}' 

    insert into #output
    select invoice_id
    from table2 with (nolock)
    where system_id = 'PrimaryColor'
    and posting_date = '{}'"""

#this is where I need help as explained below
cursor.execute(query.format(dte, dte))

output = pd.read_sql("""select *
                 from #output"""
                 , connection)

在上面,由于只有两个'{}' ,我将dte传递给query.format()两次。 但是,在我正在使用的更复杂的版本中,我有19 '{}' ,所以我想这意味着我需要将' dte'传递给'query.format{}'次。 我尝试将其作为列表传递,但它不起作用。 将变量传递给函数时,我真的需要写出变量19次吗?

考虑使用UNION ALL查询来避免临时表需求和参数化 ,您可以在其中设置qmark占位符,并在后续步骤中将值绑定到它们。 并且相同的值乘以所需数量的参数列表/元组:

dte = '2018-10-24'

# NOTE THE QMARK PLACEHOLDERS
query = """select invoice_id    
           from table1 with (nolock) 
           where system_id = 'PrimaryColor' 
             and posting_date = ? 

           union all

           select invoice_id
           from table2 with (nolock)
           where system_id = 'PrimaryColor'
             and posting_date = ?"""

output = pd.read_sql(query, connection, params=(dte,)*2)

我同意这些评论, pandas.read_sql有一个params参数,可以防止sql注入。

请参阅此文章 ,了解如何根据数据库使用它。

Pyodbc在execute方法上有相同的参数。

 # standard cursor.execute("select a from tbl where b=? and c=?", (x, y)) # pyodbc extension cursor.execute("select a from tbl where b=? and c=?", x, y) 

要回答最初的问题,即使构建SQL查询是不好的做法:

将变量传递给函数时,我真的需要写出变量19次吗?

当然你没有:

query = """select invoice_id
into #output 
from table1 with (nolock) 
where system_id = 'PrimaryColor' 
and posting_date = '{dte}' 

insert into #output
select invoice_id
from table2 with (nolock)
where system_id = 'PrimaryColor'
and posting_date = '{dte}'""".format(**{'dte': dte})

要么 :

query = """select invoice_id
into #output 
from table1 with (nolock) 
where system_id = 'PrimaryColor' 
and posting_date = '{0}' 

insert into #output
select invoice_id
from table2 with (nolock)
where system_id = 'PrimaryColor'
and posting_date = '{0}'""".format(dte)

Python 3.6+

query = f"""select invoice_id
into #output 
from table1 with (nolock) 
where system_id = 'PrimaryColor' 
and posting_date = '{dte}' 

insert into #output
select invoice_id
from table2 with (nolock)
where system_id = 'PrimaryColor'
and posting_date = '{dte}'"""

注意在“”“......”“之前使用f

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM