简体   繁体   中英

insert or replace statement not working with sqlite3 and python

Everytime I run this through the python interpreter it writes new values. for example:

name = ben
age = 10
phone = 42045042

If I run it 10 times. I get 10 duplicates in my database. I know it has to be an easy fix, but I've been working on this for hours and can't figure it out.

conn = sqlite3.connect('addressbook.db')
cur=conn.cursor()
conn.execute('''
    CREATE TABLE IF NOT EXISTS people(name TEXT,
                       age TEXT, phone TEXT, fblink TEXT)''')
conn.execute("INSERT OR REPLACE INTO people values (?, ?, ?, ?)", ben.displayPerson())
cursor = conn.execute("SELECT name, age, phone, fblink from people")
for row in cursor:
   print "NAME = ", row[0]
   print "AGE = ", row[1]
   print "PHONE = ", row[2]
   print "FACEBOOK LINK = ", row[3], "\n"
cur.close()
conn.commit()
conn.close()

There's no primary key field.

Make a primary key field.

For example:

conn.execute('''
    CREATE TABLE IF NOT EXISTS people(name TEXT primary key,
                       age TEXT, phone TEXT, fblink TEXT)''')

REPLACE is executed when UNIQUE constraint violation occurs. Without primary key (or unique ..), it does not happen.

Your table has no primary key, and hence SQLite doesn't know what it should "OR REPLACE" since it has nothing to base replacing on. Add a primary key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM