【问题标题】:How to execute psycopg query inside for loop python 3如何在for循环python 3中执行psycopg查询
【发布时间】:2020-02-14 08:57:22
【问题描述】:

**psycopg2.errors.InFailedSqlTransaction:当前事务被中止,命令被忽略直到事务块结束 ** 执行后发生错误

import pandas as pd
conn = ...
cur = conn.cursor()
fb_csv_file = "File_path"
table = pd.read_csv(fb_csv_file, encoding = 'latin1')
try:
    for index,row in table.iterrows():
        sql =  'DELETE FROM public."tbl_Name"  WHERE "col_1" =\'' +str(row['col_1']) + '\' \
                    AND "col_2"=\'' + str(row['col_2'])+'\';'     
        cur.execute(sql)
        conn.commit()
except Exception as e :             
    print("Error  : ",e)

【问题讨论】:

    标签: python-3.x pandas psycopg2


    【解决方案1】:

    这可能有用。

    这就是 Postgres 所做的when a query produces an error and you try to run another query without first rolling back the transaction。 (您可能会将其视为一项安全功能,以防止您损坏数据。)

    来源:https://stackoverflow.com/a/2979389/8074624

    【讨论】:

    • 感谢 Gaurav 的回复。我还尝试了该解决方案并在除正文中执行回滚查询。但它不是我需要的。我需要执行 DELETE 查询。
    • 我不认为您的 SQL 查询是有效的。你能打印一次你的 SQL 并给我错误的回溯(如果有的话)吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多