[英]Peewee, MySQL and INSERT IGNORE
I use Peewee as ORM in a little Python script with a MySQL DB. 我在一个带有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()
As you can see, I have the same key. 如你所见,我有相同的钥匙。 I'd like to ignore it the second time using the
on_conflict
method ( described in the API reference , but only for SQLite3), but I have this error when running the script (normal, because not implemented for MySQL): 我想第二次使用
on_conflict
方法( 在API参考中描述 ,但仅针对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")
If I remove the .on_conflict(action='IGNORE')
, MySQL doesn't like it either (duplicate key). 如果我删除
.on_conflict(action='IGNORE')
,MySQL也不喜欢它(重复键)。 How can I make peewee insert a new key or ignore it if it's a duplicate key? 如果它是重复键,我怎样才能让peewee插入新密钥或忽略它?
use db.__str__()
. 使用
db.__str__()
。 It returns 它回来了
<peewee.MySQLDatabase object at 0x7f4d6a996198>
if the connection database is MySQL and 如果连接数据库是MySQL和
<peewee.SqliteDatabase object at 0x7fd0f4524198>
if the connection database is Sqlite. 如果连接数据库是Sqlite。
So you can use an if statement like: 所以你可以使用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
I think for the MySQL database you can do something like this: 我认为对于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()
So this can be: 所以这可以是:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.