5k1*_*k17 6 python sqlite pysqlite
Gang,我开始玩pySQLite了,我正在尝试找一个例子,说明如果在db中存在新记录之前如何在插入新记录之前查询db的现有记录.我觉得我忽略了一个非常基本的功能.
谢谢!
unu*_*tbu 11
UNIQUE在创建表时使用关键字,并INSERT OR INGORE仅在记录为"new"(唯一)时使用才能插入:
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
Run Code Online (Sandbox Code Playgroud)
这里我们插入一次行:
cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
Run Code Online (Sandbox Code Playgroud)
尝试再次插入行失败:
try:
cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
except sqlite3.IntegrityError as err:
print(err)
# sqlite3.IntegrityError: column bar is not unique
Run Code Online (Sandbox Code Playgroud)
INSERT OR IGNORE仅在UNIQUE传递约束时插入记录:
cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
cursor.execute('SELECT * from foo')
data=cursor.fetchall()
print(data)
# [(1, 2)]
Run Code Online (Sandbox Code Playgroud)
要UNIQUE在多个字段上创建索引,请使用类似的内容
cursor.execute('''
CREATE TABLE foo (bar INTEGER, baz INTEGER, bing INTEGER, UNIQUE (bar, baz))''')
Run Code Online (Sandbox Code Playgroud)
以下是信息的链接
| 归档时间: |
|
| 查看次数: |
4090 次 |
| 最近记录: |