你可以使用INSERT OR REPLACE具有唯一約束更新行, 或INSERT OR IGNORE忽略插入其具有唯一約束衝突:
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()
這些sqlite的命令可能比編寫Python代碼做同樣的事情更快,但要測試這一點,你可以使用Python的timeit
模塊測試var的速度實現。例如,您可以運行
python -mtimeit -s'import test' 'test.insert_or_replace()'
與
python -mtimeit -s'import test' 'test.filter_nonunique_rows_in_Python()'
與
python -mtimeit -s'import test' 'test.insert_with_try_catch_blocks()'
謝謝。這比python中的第1點測試更有效率嗎?對於我的情況'插入或忽略'是理想的。 – xralf 2011-06-04 16:18:03
@xralf:sqlite是用C語言編寫的,因此允許sqlite執行過濾的速度最快可能比編寫自己的代碼在Python中執行相同的事情更快。 (即使Python代碼與C代碼一樣快,您仍然必須將整個表加載到一個Python對象中......)但是,由於您詢問了如何測試此聲明,我建議使用'python -mtimeit ...'。 – unutbu 2011-06-04 16:27:10