python - Peewee 示例中带有主键的 SQL 语法错误

标签 python mysql syntax-error primary-key peewee

我有一个遵循 quickstart tutorial 的简单 Peewee 数据库模型并试图将一个实例添加到数据库中。它返回错误,

'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 \'WHERE (image.url = \'foo\')\' at line 1'

我尽可能地配对代码,但我找不到我的错误。这是我的模型的一个最小且可重现的(我希望它能在我的机器上重现)示例。编辑 MySQLDatabase 调用以适合您的设置。我从一个名为“test”的空数据库开始。

from peewee import *

database = MySQLDatabase('test', **{'password': '1234', 'user': 'root'})

class BaseModel(Model):
    class Meta:
        database = database

class Image(BaseModel):
    url = CharField(primary_key=True)

database.connect()
database.create_tables([Image])

image_url = 'foo'
image_entry = Image(url=image_url)
image_entry.save()

错误是由示例代码的最后一行抛出的。如果查看我的数据库,我可以看到表“image”已成功创建。

describe image;

返回

+-------+--------------+------+-----+---------+-------+  
| Field | Type         | Null | Key | Default | Extra |  
+-------+--------------+------+-----+---------+-------+  
| url   | varchar(255) | NO   | PRI | NULL    |       |  
+-------+--------------+------+-----+---------+-------+  

如预期的那样,表仍然是空的,因为错误是在保存语句期间出现的。

select * from image:

返回

Empty set(0.00 sec)

最佳答案

这可能对您有帮助:

https://peewee.readthedocs.org/en/2.0.2/peewee/fields.html#non-integer-primary-keys

from peewee import Model, PrimaryKeyField, VarCharColumn

class UUIDModel(Model):
    # explicitly declare a primary key field, and specify the class to use
    id = CharField(primary_key=True)

Auto-increment IDs are, as their name says, automatically generated for you when you insert a new row into the database. The way peewee determines whether to do an INSERT versus an UPDATE comes down to checking whether the primary key value is None. If None, it will do an insert, otherwise it does an update on the existing value. Since, with our uuid example, the database driver won’t generate a new ID, we need to specify it manually. When we call save() for the first time, pass in force_insert = True:

inst = UUIDModel(id=str(uuid.uuid4()))
inst.save() # <-- WRONG!!  this will try to do an update

inst.save(force_insert=True) # <-- CORRECT

# to update the instance after it has been saved once
inst.save()

关于python - Peewee 示例中带有主键的 SQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573547/

相关文章:

python - 如何制作更平滑的 Perlin 噪声发生器?

php - 使用旧数据库的新版本 WordPress

javascript - 为什么我会收到此意外的字符串错误?

mongoose - 最新版本的 mongoose-validator(1.3 或 1.3.2)给出了 SyntaxError

php - [Linux, Ubuntu] : Executing a Python script with different users results in different behaviours

python - 如何在使用 ax.axis ('equal' 时强制执行 xlim 和 ylim )?

php - 如何获取已登录站点的用户的 session ID

mysql - mysql中倒序显示的记录

php - PHP解析/语法错误;以及如何解决它们

python - 在 Jupyter 实验室中连接 pytrends 时出错