python-psycopg2:在列值包含单引号时构建sql以插入多个记录时出错

0wi1tuuw  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(285)

我正在尝试将一些记录插入postgresql数据库。目前,我的代码生成一个列表(recordlst),我循环并生成一个元组,将其添加到另一个列表中,该列表被连接/转换为字符串,以生成整个sql字符串,如下所示:

'INSERT INTO table_name ("Column_1", "Column_2", ...) VALUES (...), (...) ON CONFLICT .....

也许有更好的方法生成字符串?
我当前的代码如下所示:


# START THE CONNECTION

connection = psycopg2.connect(host = hostname, 
                        user = username, 
                        password = password, 
                        dbname = db_name, 
                        port = port,
                        connect_timeout=50)  
cursor = connection.cursor()

transaction_SQL = 'INSERT INTO app_banking ("id", "transactionBankDetail_id", "date", "text", "amount", "balance", "typeTransaction", "tags", "oldCategory", "modified_by_id", "exclude_loan" ) VALUES '
sub_value_LST = list()
for x in recordLST:
    thistuple = (x["id"], x["transactionBankDetail_id"], x["date"], x["text"], x["amount"], x["balance"], x["typeTransaction"], x["tags"].replace("'", "\""), x["oldCategory"], x["modified_by_id"], x["exclude_loan"] )
    sub_value_LST.append(str(thistuple))

sub_values = ','.join(sub_value_LST)
transaction_SQL = transaction_SQL + sub_values + ' ON CONFLICT ("id") DO UPDATE SET ("tags", "oldCategory", "modified_by_id", "exclude_loan") = (EXCLUDED."tags", EXCLUDED."oldCategory", EXCLUDED."modified_by_id", EXCLUDED."exclude_loan");' 
print('app_banking\n',transaction_SQL)
try:
    transaction_SQL = transaction_SQL.replace("None", "null")
    a = cursor.execute(transaction_SQL)
except Exception as error:
    return str(error) 
......

上面的脚本生成以下字符串,该字符串通常很好,但列文本只有一个引号时除外:

INSERT INTO app_banking_transaction 
    ("id", "transactionBankDetail_id", "date", "text", "amount", "balance", "typeTransaction", "tags", "oldCategory", "modified_by_id", "exclude_loan" ) 
VALUES 
    (2419, 2, '2018-11-05', "EFTPOS MANN'S BAKERY AU", '-16.3', -105.33, '', '....', None, None, False),
    (2420, 2, '2018-11-05', 'VISA DEBIT PURCHASE CARD 5044 TT', '-28.15', -89.03, '', '...', None, None, False),

如果我删除了“eftpos mann's bakery au”的记录,效果很好,或者如果我替换了像***这样的单引号,那么我希望尽量保持字符串尽可能接近它的实际情况
我是否必须以不同的方式构建查询,如果是,如何构建?或者,我可以对字符串执行什么操作以使其工作,就好像我使用',将字符串转义为“仍然不工作”,从而得到错误:
“eftpos mann's bakery au”列不存在

7hiiyaii

7hiiyaii1#

使用插入/更新记录 cursor.execute(sql_string, tuple) ,例如,您可以尝试以下方法

transaction_SQL = (
    'INSERT INTO app_banking '
    '(id, transactionBankDetail_id, date, text, amount, balance, '
    'typeTransaction, tags, oldCategory, modified_by_id, exclude_loan) '
    'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) '
    'ON CONFLICT (id) DO UPDATE SET '
    '(tags, oldCategory, modified_by_id, exclude_loan) = (%s, %s, %s, %s)'
)

for x in recordLST:
    thistuple = (
        x["id"], x["transactionBankDetail_id"], x["date"], x["text"],
        x["amount"], x["balance"], x["typeTransaction"], x["tags"], 
        x["oldCategory"], x["modified_by_id"], x["exclude_loan"], 
        x["tags"], x["oldCategory"], x["modified_by_id"], x["exclude_loan"]
    )
    cursor.execute(transaction_SQL, thistuple)
connection.commit()

相关问题