我正在尝试INSERT or REPLACE INTO t1
是否name
已经存在。我知道如果设置了 id 则替换将起作用,但我需要它对名称做出反应。
import sqlite3
def insert(name):
cur.execute('INSERT OR REPLACE INTO t1(name) VALUES(?)', [name])
def select():
return cur.execute('SELECT * FROM t1').fetchall()
conn = sqlite3.connect('test')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS t1')
cur.execute('''CREATE TABLE IF NOT EXISTS t1(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)''')
insert('jack')
insert('jack')
insert('jack')
print select()
输出
[(1, u'jack'), (2, u'jack'), (3, u'jack')]