[英]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)
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.