在Python中加入两个SQL字符串列表

时间:2014-05-12 12:10:11

标签: python sql postgresql psycopg2

我目前正在python中加入两个列表,使用此代码生成一个输入数据库的字符串:

newDataString = ', '.join("%s=\'%s\'" % t for t in zip(tableColumns,data))

其中tableColumns是列的列表,data是与列相关的数据列表。我正在加入这些以进行更新。

一切正常,除非数据列表中的值=无

cur.execute("UPDATE "+table+" SET "+str(newDataString)+" FROM "+tempTable+" WHERE "+generatePrimaryKeyMatches(primaryKey, table))
psycopg2.DataError: invalid input syntax for type date: "None"
LINE 1: ...ION RESEARCH & REP', suff='None', hon='None', dob='None', na...

我想我在这里需要一个if语句来检查数据中的每个值,然后才将它放入连接中,并且应该区别对待(即没有\')如果data = None,但我不能因为我的生活想出来了。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我认为如果将其拆分为两个步骤会更容易:

newDataList = []
for t in zip(tableColumns, data):
    if t[1] is not None:
        newDataList.append("{0}=\'{1}\'".format(*t))
    else:
        # ...deal with None
newDataString = ", ".join(newDataList)

注意我已将过时的%格式切换为str.format