在Python中,是否可能在必要时将某个条件作为参数传递给函数?例如:完整的if条件:
# /!\ checking if customer_name is NULL (NOT NULL field in destination database)
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
我正在编写一个脚本,用于自动化从mysql到postgresql的数据迁移。一些表在两个数据库(源和目标)中具有相同的结构,而其他表则在结构上不同,还有一些仅具有数据类型差异。
我试图理解是否可能将条件“注入”到函数中,以便在所有上述段落中使用相同的代码片段。每次条件都会有所不同。
以下是一个示例(我正在调查注入的可能性的代码片段为黄色->将其作为参数传递):
def migrate_table(select_query, insert_query, tmp_args):
# Cursors initialization
cur_psql = cnx_psql.cursor()
cur_msql.execute(select_query)
args = []
for row in cur_msql:
# /!\ checking if customer_name is NULL (NOT NULL field in destination database)
if row['customer_name'] == NULL:
row['customer_name'] = row['contact_name']
args.append(cur_psql.mogrify(tmp_args, row))
args_str = ','.join(args)
if len(args_str) > 0:
try:
cur_psql.execute(insert_query + args_str)
except psycopg2.Error as e:
print "Cannot execute that query", e.pgerror
sys.exit("Leaving early this lucky script")
## Closing cursors
cur_psql.close()
实际上,我以这种方式调用我的函数:
migrate_compatable(
"SELECT customer_id, customer_name, contact_name, address, city, postal_code, country FROM mysqlcustomers",
"INSERT INTO psqlcustomers (customer_id, customer_name, contact_name, address, city, postal_code, country"
"(%(customer_id)s, %(customer_name)s, %(contact_name)s, %(address)s, %(city)s, %(postal_code)s, %(country)s)"
)
我想知道是否有可能添加一个接受完整条件作为输入的参数
lambda
来做你想要的事情。 - jonrsharpe