2017-01-24 7 views
1

私はMySQLデータベースを備えたPythonの小さなスクリプトでORMとしてPeeweeを使用します。Peewee、MySQLとINSERT IGNORE

#!/usr/bin/python3 
#coding: utf-8 

import peewee 
from peewee import * 

db = MySQLDatabase(**config) 
class Foo(peewee.Model): 
    bar = peewee.CharField(unique=True, null=False) 
    class Meta: 
     database = db 

try: 
    Foo.create_table() 
except: 
    pass 

foo_data = [{'bar':'xyz'},{'bar':'xyz'}] 
Foo.insert_many(foo_data).on_conflict(action='IGNORE').execute() 

ご覧のとおり、私は同じキーを持っています。私は(だけSQLite3のため、described in the API referenceon_conflictメソッドを使用して、それをもう一度無視したいのですが、(MySQLのために実装されていないので、通常の)私は、スクリプトを実行しているこのエラーを持っている:

peewee.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OR IGNORE INTO `foo` (`bar`) VA' at line 1") 

の場合私は.on_conflict(action='IGNORE')を削除しますが、MySQLはそれを好きではありません(重複キー)。ピューニーに新しい鍵を挿入させたり、鍵が重複している場合は無視したりするにはどうすればよいですか?

答えて

0

db.__str__()。接続データベースがSqliteをされた場合、接続データベースはMySQLと

<peewee.SqliteDatabase object at 0x7fd0f4524198> 

ある場合は

<peewee.MySQLDatabase object at 0x7f4d6a996198> 

を返します。

あなたのようなif文を使用することができますので:だから、これは可能

for data in foo_data: 
    for k,v in data.items(): 
     if (Foo.select(Foo.bar).where(Foo.bar == v).count()) == 0: 
      Foo.insert(bar=v).execute() 

if 'SqliteDatabase' in db.__str__(): 
    Foo.insert_many(foo_data).on_conflict(action='IGNORE').execute() 
elif 'MySQLDatabase' in db.__str__(): 
    with db.atomic(): 
     for data in foo_data: 
      for k, v in data.items(): 
       if (Foo.select(Foo.bar).where(Foo.bar == v).count()) == 0: 
        Foo.insert(bar=v).execute() 

if 'SqliteDatabase' in db.__str__(): 
    Foo.insert_many(foo_data).on_conflict(action='IGNORE').execute() 
elif 'MySQLDatabase' in db.__str__(): 
    try: 
     Foo.insert_many(foo_data).execute() # or whatever you want with MySQL 
    except: 
     pass 

を私はMySQLデータベースのためにあなたは、このような何かを行うことができると思います