python code to find duplicate row in sqlite database

43

import sqlite3
# it will create a databse with name sqlite.db
connection= sqlite3.connect('sqlite.db') 
cursor= connection.cursor()
table_query = '''CREATE TABLE  if not Exists Student
               (Name text, Course text, Age real)'''
       

cursor.execute(table_query)        
# student list 

students_data = [
 ['AlixaProDev','CS',19],
 ['Alixawebdev','BBa',21],
  ['AskALixa','Software',22],
  ['AskALixa','Software',22]
]
insert_q = []

# creating the insert query for each student
for std_data in students_data:
    name = std_data[0]
    course = std_data[1]
    age = std_data[2]
    q=f"INSERT INTO Student VALUES ('{name}','{course}','{age}')"
    # check if a row is already exist 
    cursor.execute("SELECT rowid FROM Student WHERE Name = ?", (name,))
    db_result=cursor.fetchall()
    if len(db_result)==0:
        cursor.execute(q)
        print('Studnet Data inserted Successfully')
    else:
        print('Student %s found with rowids %s'%(name,','.join(map(str, next(zip(*db_result))))))
  
        
# you need to commit changes as well
connection.commit()
# you also need to close  the connection
connection.close()Copy Code

Comments

Submit
0 Comments