Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x sqlite3,IntegrityError:插入值时唯一约束失败_Python 3.x_Sqlite - Fatal编程技术网

Python 3.x sqlite3,IntegrityError:插入值时唯一约束失败

Python 3.x sqlite3,IntegrityError:插入值时唯一约束失败,python-3.x,sqlite,Python 3.x,Sqlite,为了防止数据库变得太大,我只希望sqlite插入尚未插入的值。我做了一些搜索,发现最好的方法是使用一个唯一的约束。在我看来,sqlite在插入一个非唯一的值时崩溃,我如何避免这个错误并继续下一次提交 下面是一些相关代码 sql = sqlite3.connect('submissions.db') cur = sql.cursor() cur.execute('CREATE TABLE IF NOT EXISTS some_table(id TEXT UNIQUE)') sql.commit()

为了防止数据库变得太大,我只希望sqlite插入尚未插入的值。我做了一些搜索,发现最好的方法是使用一个唯一的约束。在我看来,sqlite在插入一个非唯一的值时崩溃,我如何避免这个错误并继续下一次提交

下面是一些相关代码

sql = sqlite3.connect('submissions.db')
cur = sql.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS some_table(id TEXT UNIQUE)')
sql.commit()

for thing in things:
    try:
        # Do some stuff
    except AttributeError:
        pass

    cur.execute('INSERT INTO some_table VALUES(?)', [thing])
    sql.commit()
以下是回溯:

Traceback (most recent call last):
  File "D:\Directory\Python\Projects\Oddshotcrawler for Reddit, globaloffensive\oddshotcrawler.py", line 62, in <module>
    oddshotcrawler()
  File "D:\Directory\Python\Projects\Oddshotcrawler for Reddit, globaloffensive\oddshotcrawler.py", line 54, in oddshotcrawler
    cur.execute('INSERT INTO oldposts VALUES(?)', [thing])
sqlite3.IntegrityError: UNIQUE constraint failed: some_table.id
[Finished in 7.1s with exit code 1]
回溯(最近一次呼叫最后一次):
文件“D:\Directory\Python\Projects\oddshotclawler for Reddit,globaloffensive\oddshotclawler.py”,第62行,在
oddshotcrawler()
Oddshotcrawler中的文件“D:\Directory\Python\Projects\Oddshotcrawler for Reddit,globaloffensive\Oddshotcrawler.py”,第54行
cur.execute('INSERT INTO oldposts value(?),[thing])
sqlite3.IntegrityError:唯一约束失败:some_table.id
[在7.1s中完成,退出代码为1]

插入
更改为
插入或忽略

cur.execute('INSERT OR IGNORE INTO oldposts VALUES(?)', [submID])
将“插入”更改为“插入或替换” 这样更好

Update_Table = """INSERT OR REPLACE INTO station_statusDB VALUES(?, ?, ?, ?);"""
with sql.connect(station_statusDB) as Conn:
    print("Connected to:", station_statusDB)
    Conn.execute(New_Station_Table)
    while Client_Flag != 0:
        print("Updating Station Database...")
        Conn.execute(Update_Table, (ClientID, Client_date, Client_Alarm, Client_Water))
        print("Done!, Saving...")
        Conn.commit()
. 这个答案完全解决了我的问题。如果行已存在,则直接处理要替换的情况。