本文由Markdown語法編輯器編輯完成。
1. 需求:
現在有一個Python的需求需要實現:
就是實現連接一次數據庫,就能夠執行多條SQL語句,而且這個SQL語句是需要通過調用者將每一次執行的參數傳入進來,組合成一條完整的SQL語句再去執行。
經過初步研究,傳入參數時,通過數組的形式,數組中的每一個元素則是一個元組tuple(因為SQL中需要填入的參數可能是多個,所以需要通過元組的形式傳入)。
比如SQL語句的形式為:
basic_sql = 'SELECT * FROM dcm4chee.series se where se.body_part like "%{}%" and se.modality = "{}"'
在這條SQL中,有兩個變量需要傳入,分別用{}表示,一個是序列的body_part, 一個是序列的modality。准備傳入的參數為:
[('Chest', 'CT'), ('Lung', 'MRI'), ('Leg', 'DR')]等。
希望通過以下的格式化函數,將參數傳入:
SELECT * FROM dcm4chee.series se where se.body_part like "%{}%" and se.modality = "{}".format(param1, param2) 這樣。
2. 函數實現:
雖然看起來這個需求非常明確,也比較簡單。但是實現起來,還是花費了我好長的時間。究其原因,主要的困惑就是如何能夠將這個參數傳入到SQL中,並且去執行SQL。
2.1 思路一:
在基於需求中提到的那個解決思路,我希望是拼接字符串,將拼接后的整個字符串作為完整的SQL語句,然后執行生成結果。
def execute_multi_sql(self, sql, params_list):
result_list = []
try:
self._db_connection = self._db_connection_pool.connection()
self._db_cursor = self._db_connection.cursor()
for params in params_list:
combined_sql = []
combined_sql.append(sql)
combined_sql.append('.format(')
combined_sql.append(','.join(map(str, params)))
combined_sql.append(')')
combined_sql = ''.join(combined_sql)
logger.debug("executing sql: %s" % combined_sql)
self._db_cursor.execute(combined_sql)
result = self._db_cursor.fetchall()
logger.debug(u"SQL語句已經被執行, 結果是:\n %s" % str(result))
result_list.append(result)
except Exception as e:
logger.exception(u"執行sql語句時,發生了錯誤: %s", e.message)
raise
finally:
self._db_connection.close()
return result_list
但是在執行這個函數的時候,會報異常,異常說明是:tuple out of bounds.
以下是問題產生的原因:
2.2 思路二:
通過google搜索,最終找到的解決方案是如下鏈接所示:
expanding tuples into arguments.
https://stackoverflow.com/questions/1993727/expanding-tuples-into-arguments
未完待續......