python 字典 拼接SQL語句
阿新 • • 發佈:2019-04-17
def () 表名 數據庫 對象 nbsp return count urn f = "(" + "{}," * (fields_count - 1) + "{})"
v = "(" + "‘{}‘," * (fields_count - 1) + "‘{}‘)"
sql = "insert into {} " + f + " VALUES " + v
sql = sql.format(table_name, *fields, *values)
return sql
def gen_sql(table_name, data):
"""
:param table_name: 表名稱
:param data: 字典對象 key為字段(要與數據庫字段一樣), value為插入值
:return: 拼接好的sql語句
"""
fields = list()
values = list()
for k, v in data.items():
if v: # 沒有值, 就不插入
fields.append(k)
values.append(v)
fields_count = len(fields)
v = "(" + "‘{}‘," * (fields_count - 1) + "‘{}‘)"
sql = "insert into {} " + f + " VALUES " + v
sql = sql.format(table_name, *fields, *values)
return sql
python 字典 拼接SQL語句