How to avoid duplication of data when inputting from Python to SQLite.

!/usr/bin/env python
 -*- coding: utf-8 -*-

import sys
import codecs
import sqlite3
import types

conn = sqlite3.connect("test.db" , isolation_level=None)
cur = conn.cursor()

 #Table initialization
conn.execute("create table list(id integer primary key,name text)")

 new_list = ['a','b','c','a'] # <= The last'a' is duplicated.

for i in new_list:
  sql = "select name from list where name LIKE '"+str(i)+"';"
  result =  conn.execute(sql).fetchone()
 # types.NoneType is returned. => The input data does not have the same content
  if type(conn.execute(sql).fetchone()) == types.NoneType:
    sql = "insert into  list(name) values('"+str(i)+"');"
    conn.execute(sql)

sql = "select * from list;"
print conn.execute(sql).fetchall()

>>>[(1, 'a'), (2, 'b'), (3, 'c')]












        

Recommended Posts