如何在executemany中自动跳过重复的raw?

2024-04-19 20:45:44 发布

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

我为我的表设置了一个主键。现在我想在执行任意插入时自动跳过重复的raw。 我该怎么办?这是我的代码和注释。谢谢你们。你知道吗

cmd = \
'''
CREATE TABLE test(
id INTEGER PRIMARY KEY NOT NULL,
value INTEGER
)
'''
c.execute(cmd)
# now we have key = 1,2,3,4
c.executemany("INSERT INTO test VALUES (%s,%s)", [(1,100),
                                                  (3,100),
                                                  (2,100),
                                                  (4,100),])
# I want script automatically skip repeated row (1,200)
# if I add a try, except here, only the (5, 100) has been inserted
# because script jump out when exception raised
c.executemany("INSERT INTO testVALUES (%s, %s)", [(5,100),
                                                  (1,200),
                                                   (6,100)])

Tags: key代码testcmdidrawcreatetable
1条回答
网友
1楼 · 发布于 2024-04-19 20:45:44

如果您想使用那种类型的INSERT语法,我建议插入executemany,在循环内部使用execute,在每个循环之后使用commit(因为如果您不commit,那么在异常发生后,您将丢失先前插入的项)。你知道吗

类似于(其中conn是您的连接对象):

for item_tuple in [(1,100), (3,100), (2,100), (4,100)]:
    try:
        c.execute("INSERT INTO test VALUES (%s,%s)", item_tuple[0],
                   item_tuple[1])
        conn.commit()
    except Exception as e:
        print "failed to insert: {0}".format(e)
        conn.rollback()
        # continue on to next item

这样,如果遇到异常,您可以继续、吞咽(并打印)异常(如果需要,您可以使用regex搜索异常文本以寻找更窄的字符串,这样您就不会吞咽每个异常,因为这样做在某些情况下可能是不需要的),然后rollback这样您就可以继续使用连接(否则您将得到尝试将连接与中止的事务一起使用时出错)。你知道吗

另一个选项,不一定要求您对每个项目commit

您可以使用INSERT的形式,它将SELECT语句作为输入,并且您可以对它进行结构设计,以便它选择所需的值,但是检查它们是否已经首先出现,因此如果已经出现,select with的结果将是空集,并且不会插入任何内容。(由于MVCC的原因,在具有多个连接和事务的情况下,这可能会有问题,但是如果您是唯一一个为该检查而插入到表中的人,那么就可以了)。你知道吗

比如说:

for item_tuple in [(1,100), (3,100), (2,100), (4,100)]:
    c.execute("INSERT INTO test VALUES (%s,%s)
                SELECT %s, %s
                WHERE NOT EXISTS (SELECT 1
                                  FROM test
                                  WHERE value = %s
                                 )",
               item_tuple[0], item_tuple[1], item_tuple[0],
               item_tuple[1], item_tuple[1])

相关问题 更多 >