10
12

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.

MySQL INSERT重複あるならUPDATEかIGNORE

Last updated at Posted at 2019-05-10

基本INSERT重複あるならUPDATEかIGNORE

Pythonでデータ処理してたらMySQLでduplicate entryのようなエラー発生。重複ある場合にINSERTしたので発生したようです。
重複あったら上書きしてしまうか無視する方法を書きます。
※勉強中の身なので細かいところは注意してください

ON DUPLICATE KEY UPDATE

REPLACE INTOでもできるみたいだが、構造上DELETEされるので削除権限与える必要あり、TIMESTAMPの問題あるのでON DUPLICATE KEY UPDATE使う方がいいらしい。

1行ずつINSERTでなく一括にて

.sql
INSERT INTO
    sampletable (Id, Name, LogDate, LogTime, LogMilliSecond, LogValue)
    VALUES(%s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
    Id = VALUES(Id),
    Name = VALUES(Name),
    LogDate = VALUES(LogDate),
    LogTime = VALUES(LogTime),
    LogMilliSecond = VALUES(LogMilliSecond),
    LogValue = VALUES(LogValue)

この例は単純にデータがあったらUPDATEするだけですが、重複していたら数値+1したいとか、挿入する文字を変更したいなどもに使うのが普通かと思います。
INSERT ... ON DUPLICATE KEY UPDATE Syntax

今回の例では別にエラー出ないで重複は無視されればいいのでINSERT IGNORE INTOも使えます

INSERT IGNORE INTO

.sql
INSERT IGNORE INTO
    sampletable (Id, Name, LogDate, LogTime, LogMilliSecond, LogValue)
    VALUES(%s, %s, %s, %s, %s, %s)

重複データが入ってくるのが基本的にない場合にはこれでもいいかも。
参考:INSERT Syntax

ただ、なんか怪しい雰囲気あったので調べたらやはり怪しい場合あるみたい
kamipo TRADITIONALでは防げないINSERT IGNOREという名の化け物

最後にPYTHONコードこんな感じで登録

insert.py
import MySQLdb
conn = MySQLdb.connect(
user='username',
passwd='pass',
host='localhost',
db='sample_db')

cur = conn.cursor()
sql = '''
INSERT IGNORE INTO
    sampletable (Id, TagName, LogDate, LogTime, LogMilliSecond, LogValue)
    VALUES(%s, %s, %s, %s, %s, %s)
'''
# ↓サンプルデータ。ここをデータ読み込み処理入れ替え
datas = [
[1, 'Status1','19/05/09','02:40:00',0,1],
[2, 'Status1','19/05/09','07:40:00',0,2],
[3, 'Status1','19/05/09','12:30:00',0,1],
[4, 'Status1','19/05/09','17:30:00',0,2],
[5, 'Status1','19/05/09','21:30:00',0,1],
[6, 'Status1','19/05/09','23:30:00',0,2],
]

try:
    cur.executemany(sql, datas)    # バルクインサート
    print(str(cur.rowcount) + "件登録")
    conn.commit()
    
except Exception as e:
        print(e)
        
finally:
    # 接続を閉じる
    cur.close
    conn.close
10
12
0

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
10
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?