在Python Psycopg2查询中转义字符

时间:2017-12-12 00:38:33

标签: python psycopg2

我试图转义字符以在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_values()找到了可能的答案 积分:https://repo.spring.io/libs-snapshot

将性能提高700%

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

2 个答案:

答案 0 :(得分:1)

这样的事情:

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)

这可能符合您的需求:

>>> "INSERT INTO p_reply (parent_id, comment) VALUES %s;" % ", ".join(str(entry) for entry in [("parent_id1", "comment1"), ("parent_id2", "comment2")])
"INSERT INTO p_reply (parent_id, comment) VALUES ('parent_id1', 'comment1'), ('parent_id2', 'comment2');"

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

答案 1 :(得分:0)

你应该像这样逃跑:

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))