2

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()
2
  • Why are you using INSERT OR REPLACE INTO ...? Shouldn't it be just INSERT INTO? Commented Oct 26, 2013 at 2:27
  • insert into gives me the same problem, that's why i tried insert or replace. Commented Oct 26, 2013 at 2:42

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

it has the conn.commit
@user2905382, I misunderstood your question. I updated the answer.
i have no idea what a primary key does, but i will try this. also i reworded my question
I don't know why or how, but that fixed it. You are a genius!
@user2905382, Primary key is like the identifier of the row.
|
1

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.

1 Comment

A primary key is just one of the methods to get a UNIQUE constraint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.