1. 程式人生 > >python 字典 拼接SQL語句

python 字典 拼接SQL語句

def () 表名 數據庫 對象 nbsp return count urn

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)

   f = "(" + "{}," * (fields_count - 1) + "{})"
   v = "(" + "‘{}‘," * (fields_count - 1) + "‘{}‘)"
   sql = "insert into {} " + f + " VALUES " + v
   sql = sql.format(table_name, *fields, *values)
  return sql

python 字典 拼接SQL語句