Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Avoid duplicate entries in SQLite3

I am learning Sqlite here I am trying to create a simple database with username & password , The database gets created successfully & I am able too see values but everytime I am running the script same item is getting added in db how can I avoid duplicates here

import sqlite3

print("Creating Db ")
conn = sqlite3.connect("lp.db")
print("Db created successfully")
try:
    conn.execute(
        """CREATE TABLE Users
     (
    "username"  TEXT ,
    "password"  TEXT
    );"""
    )
except Exception as e:
    print(e)

else:
    print("Table created successfully")

cur = conn.cursor()

# The result of a "cursor.execute" can be iterated over by row
row = cur.execute('SELECT * FROM Users').fetchall()
if not row:
    print("Empty")
else:
    print("row")

conn.execute("INSERT INTO Users (username,password) VALUES ('lp',1234 )")
conn.commit()
row = cur.execute('SELECT * FROM Users').fetchall()
if not row:
    print("Empty")
else:
    print(row)

print("Done")
conn.close()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Delete old database file & Just Add UNIQUE in front of username

import sqlite3

print("Creating Db ")
conn = sqlite3.connect("lp.db")
print("Db created successfully")
try:
    conn.execute(
        """CREATE TABLE Users
     (
    "username"  TEXT UNIQUE ,
    "password"  TEXT
    );"""
    )
except Exception as e:
    print(e)

else:
    print("Table created successfully")

cur = conn.cursor()


conn.execute("INSERT OR IGNORE INTO Users  (username,password) VALUES ('lp2',1234 )")
conn.commit()
row = cur.execute('SELECT * FROM Users').fetchall()
if not row:
    print("Empty")
else:
    print(row)
    print(conn.total_changes)
# Be sure to close the connection

print("Done")
conn.close()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading