用字符串填充占位符

时间:2015-08-05 04:45:14

标签: python mysql string

我想到了一种创建MySQL语句的动态方法,它必须填充从外部函数传递的值。

def check_id(table_name=None, *args):
""""""
  args = args[0]
  # print args, type(args), len(args)
  vals = [ tuple(elem.values()) for elem in args ]

  if isinstance(args, list):
    columns = []
    for idx, key in enumerate(args[0].keys()):
      if idx == len(args[0].keys()):
        columns.append((key, "= '%s'"))
      columns.append((key, "= '%s', AND"))

    columns = ' '.join("`%s` %s" % x for x in columns)
   else:
     print "NOT A LIST"
  sql = """SELECT id FROM %(table_name)s
         WHERE %(columns)s;""" % {'table_name':table_name, 'columns':vals}
  print sql

列将按如下方式创建:

`size` = '%s', AND `resource_group_id` = '%s', AND `description` = '%s', AND `name` = '%s', AND `created` = '%s', AND `url` = '%s', AND `format` = '%s', AND `res_geo_0` = '%s', AND `tracking_summary_total` = '%s', AND `revision_timestamp` = '%s', AND `res_geo_1` = '%s', AND `state` = '%s', AND `last_modified` = '%s', AND `webstore_last_updated` = '%s', AND `url_type` = '%s', AND `position` = '%s', AND `revision_id` = '%s', AND `webstore_url` = '%s', AND `resource_type` = '%s', AND `tracking_summary_recent` = '%s', AND

我如何填写占位符'%s'来自vals的值。任何的想法?这些甚至被视为python的占位符吗?或者这是一种错误的方法吗?

0 个答案:

没有答案