我在一个带有MySQL DB的小Python脚本中使用Peewee作为ORM。
#!/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()如你所见,我有同样的钥匙。我想使用on_conflict方法第二次忽略它(described in the API reference,但仅适用于SQLite3),但在运行脚本时出现以下错误(正常,因为不是为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")如果我删除这个键,MySQL也不喜欢它(重复的键)。如何让peewee插入一个新的密钥,或者如果它是一个重复的密钥,则忽略它?
发布于 2017-01-27 23:31:04
使用db.__str__()。它返回
<peewee.MySQLDatabase object at 0x7f4d6a996198>如果连接数据库为MySQL,并且
<peewee.SqliteDatabase object at 0x7fd0f4524198>如果连接数据库是Sqlite。
因此,您可以使用如下的if语句:
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数据库,您可以这样做:
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()https://stackoverflow.com/questions/41829548
复制相似问题