misszm

以前以为错过也很美, 想在很后悔

python 字典 拼接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)
   f = "(" + "{}," * (fields_count - 1) + "{})"
   v = "(" + "'{}'," * (fields_count - 1) + "'{}')"
   sql = "insert into {} " + f + " VALUES " + v
   sql = sql.format(table_name, *fields, *values)
  return sql

posted on 2019-04-17 21:03  宋喜阳  阅读(3227)  评论(0编辑  收藏  举报

导航