insert into sqlite table with unique column

后端 未结 2 1614
無奈伤痛
無奈伤痛 2021-02-06 07:36

I\'m inserting values into my table (from python code) as follows:

cur.execute(\"insert into t(a, b, c) values (?, ?, ?)\", (a, b, c))

There is

相关标签:
2条回答
  • 2021-02-06 08:22

    You could use INSERT OR REPLACE to update rows with a unique constraint, or INSERT OR IGNORE to ignore inserts which conflict with a unique constraint:

    import sqlite3
    
    def insert_or_replace():
        # https://sqlite.org/lang_insert.html
        connection=sqlite3.connect(':memory:')
        cursor=connection.cursor()
        cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
        cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
        cursor.execute('INSERT OR REPLACE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
        cursor.execute('SELECT * from foo')
        data=cursor.fetchall()
        print(data)
        # [(1, 3)]
    
    
    def on_conflict():
        # https://sqlite.org/lang_insert.html
        connection=sqlite3.connect(':memory:')
        cursor=connection.cursor()
        cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
        cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
        cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
        cursor.execute('SELECT * from foo')
        data=cursor.fetchall()
        print(data)
        # [(1, 2)]    
    
    insert_or_replace()
    on_conflict()
    

    These sqlite commands are probably faster than writing Python code to do the same thing, though to test this you could use Python's timeit module to test the speed of various implementations. For example, you could run

    python -mtimeit -s'import test' 'test.insert_or_replace()'
    

    versus

    python -mtimeit -s'import test' 'test.filter_nonunique_rows_in_Python()'
    

    versus

    python -mtimeit -s'import test' 'test.insert_with_try_catch_blocks()'
    
    0 讨论(0)
  • 2021-02-06 08:28

    Depends :)

    If there is only one inserter the 1 might be the most efficient.

    If there are several inserters you have to use 2 as under 1 you could test and seem OK but another inserter adds the C value you have so it fails

    0 讨论(0)
提交回复
热议问题