Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典创建SQL查询_Python_Mysql_Sql_Dictionary - Fatal编程技术网

Python 从字典创建SQL查询

Python 从字典创建SQL查询,python,mysql,sql,dictionary,Python,Mysql,Sql,Dictionary,我有一个函数来更新数据库(MySQL)中的条目,它需要尽可能动态 该函数允许API用户传递记录的id,然后kwargs处理要更改的值(传递的值数量没有限制) 假设我从kwargs那里得到这本字典 {'hello':'world', 'foo':'bar'} 有没有一种方法可以在update语句中使用它 UPDATE myTable SET key_n = val_n, key_n+1 = val_n+1, ... WHERE id = the_id_passed_to_the_function

我有一个函数来更新数据库(MySQL)中的条目,它需要尽可能动态

该函数允许API用户传递记录的id,然后kwargs处理要更改的值(传递的值数量没有限制)

假设我从kwargs那里得到这本字典

{'hello':'world', 'foo':'bar'}
有没有一种方法可以在update语句中使用它

UPDATE myTable
SET key_n = val_n, key_n+1 = val_n+1, ...
WHERE id = the_id_passed_to_the_function
提前感谢。

试试这个:

def UpdateQuery(data,where):
    if isinstance(data, dict) and where:
        vals = ','.join(["%s=?" %(k) for k,v in data.iteritems()])
        query = "update myTable set %s where id=?" % (vals)
        res = cr.execute(query,where)
试试这个:

def UpdateQuery(data,where):
    if isinstance(data, dict) and where:
        vals = ','.join(["%s=?" %(k) for k,v in data.iteritems()])
        query = "update myTable set %s where id=?" % (vals)
        res = cr.execute(query,where)
那么:

foo = kwargs['bar']
id = 1
if foo:
    k = foo.keys()
    q = '''UPDATE myTable'''
    q += ','.join('SET {0}=%s'.format(i) for i in k)
    q += 'WHERE id = %s'
    cur.execute(q,tuple(foo[i] for i in k)+(id,))
需要注意的几点:

  • 因为字典是无序的,所以我们首先获取一个键列表
  • 而不是将值直接放入查询中;你应该把它们传进来。同样,我们会逐步遍历相同的键列表,以便值与列名匹配
  • 最后,我们将id添加到查询的有序参数集中
  • 那么:

    foo = kwargs['bar']
    id = 1
    if foo:
        k = foo.keys()
        q = '''UPDATE myTable'''
        q += ','.join('SET {0}=%s'.format(i) for i in k)
        q += 'WHERE id = %s'
        cur.execute(q,tuple(foo[i] for i in k)+(id,))
    
    需要注意的几点:

  • 因为字典是无序的,所以我们首先获取一个键列表
  • 而不是将值直接放入查询中;你应该把它们传进来。同样,我们会逐步遍历相同的键列表,以便值与列名匹配
  • 最后,我们将id添加到查询的有序参数集中