Python 字典映射到 SQL 具有列表理解的字符串

Python dictionary map to SQL string with list comprehension

我有一个 python 字典,可以将列名称从源 table 映射到目标 table。

注意:这个问题在之前的线程中针对不同的查询字符串得到了回答,但是这个查询字符串更复杂,我不确定它是否可以使用相同的列表理解方法生成。

词典:

tablemap_computer = {
    'ComputerID' : 'computer_id',
    'HostName' : 'host_name',
    'Number' : 'number'
}

我需要动态生成以下查询字符串,以便在将新的列名称对添加到字典时正确更新。

(ComputerID, HostName, Number) VALUES (%(computer_id.name)s, %(host_name)s, %(number)s)

我从列表理解开始,但到目前为止我只能使用这种技术生成查询字符串的第一部分。

queryStrInsert = '('+','.join([tm_val for tm_key, tm_val in tablemap_incident.items()])+')'
print(queryStrInsert)

#Output
#(computer_id,host_name,number)
#Still must generate the remaining part of the query string parameterized VALUES

如果我理解你想要达到的目的,你可以这样完成:

holder = list(zip(*tablemap_computer.items()))

"insert into mytable ({0}) values ({1})".format(",".join(holder[0]), ",".join(["%({})s".format(x) for x in holder[1]]))

这应该产生:

# 'insert into mytable (HostName,Number,ComputerID) values (%(host_name)s,%(number)s,%(computer_id)s)'

希望对您有所帮助。