6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonからSQLiteに入力する時にデータを重複させない方法。

Posted at

#!/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()

 #テーブルの初期化
conn.execute("create table list(id integer primary key,name text)")

new_list = ['a','b','c','a'] #<= 最後の'a'が重複している。

for i in new_list:
  sql = "select name from list where name LIKE '"+str(i)+"';"
  result =  conn.execute(sql).fetchone()
 #types.NoneTypeが返ってくる。 =>入力データに同じ内容が無い
  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')]


6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?