Python Psycopg2查询中的转义字符

2024-04-20 00:45:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图转义字符在python中创建一个事务块,然后一次提交,但没有成功。。。在

例如:

def transaction_block(sql):
    global sql_transaction
    sql_transaction.append(sql)
    if len(sql_transaction) > 1000:
        db.execute('BEGIN TRANSACTION')
        for s in sql_transaction:
            try:
                db.execute(s)
            except Exception as e:
                print(e)
        db.commit()
        sql_transaction = []

def sql_insert_comment(parentid,comment):
    try:
        sql = "INSERT INTO p_reply (parent_id, comment) VALUES ('{}','{}');".format(parentid, comment)
        transaction_block(sql)
    except Exception as e:
        print('error s02',str(e))

我应该如何调整它以使用%s以便可以全部退出?或者有更好的方法来实现这个目标?在

更新1

使用execute\u values()找到可能的答案 贷方:https://billyfung.com/writing/2017/06/improving-multiple-inserts-with-psycopg2/

700%性能提升

如果你知道更好的方法,请告诉我;)


Tags: 方法executedbsqldefasexceptioncomment
2条回答

你应该这样逃跑:

try:
    sql = "INSERT INTO p_reply (parent_id, comment) VALUES (%s,%s)"
    db.execute(sql,[parent_id,comment])
except Exception as e:
    print('error s02',str(e))

这样的事情怎么样:

entries = [
    ("parent_id1", "comment1"),
    ("parent_id2", "comment2"),
    ("parent_id3", "comment3")
]
query = "INSERT INTO p_reply (parent_id, comment) VALUES %s;" % ", ".join(str(entry) for entry in entries)

是吗?在

可能适合您的需求:

^{pr2}$

如果数据集中有整数(parent_id值),则可能还需要将其转换为str或修改格式化字符串以添加'。在

相关问题 更多 >