gpt4 book ai didi

python Flask SQLAlchemy 将数据插入 mysql

转载 作者:行者123 更新时间:2023-11-29 17:24:35 25 4
gpt4 key购买 nike

我想将测试数据插入到mysql用户表中。我第一次可以在python shell中添加数据,但我不知道如何在新的shell环境中插入数据:

MariaDB [python]> select * from users;
+----+----------+---------+
| id | username | role_id |
+----+----------+---------+
| 1 | John | 1 |
| 2 | Mary | 2 |
| 3 | Terry | 3 |
| 4 | test_user| 1 | (I want insert 'test_user' into mysql like this)

MariaDB [python]> select * from roles;
+----+-----------+
| id | name |
+----+-----------+
| 1 | Admin |
| 2 | Moderator |
| 3 | User |
+----+-----------+

[root@docker1 namecard]# /root/namecard/bin/python3 manage.py shell
>>> admin_role = Role(name='Admin')
>>> user_test = User(username='test_user', role=admin_role)
>>> db.session.add(user_test)
>>> db.session.commit()
============================================================
Traceback (most recent call last):
File "/root/namecard/lib/python3.5/site-packages/sqlalchemy/engine/base.py", line 1 context)
... ...
sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry 'Admin' for key 'name'") [SQL: 'INSERT INTO roles (name) VALUES (%(name)s)'] [parameters: {'name': 'Admin'}] (Background on this error at: http://sqlalche.me/e/gkpj)
============================================================

我知道系统报告重复条目Admin错误,但我不知道如何在python shell环境中将数据插入到mysql表中。

这是我的models.py 文件:

[root@docker1 namecard]# cat app/models.py
from . import db
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')

def __repr__(self):
return '<Role %r>' % self.name
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), unique=True, index=True)
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

def __repr__(self):
return '<User %r>' % self.username

最佳答案

您的role 表已包含Admin 条目,因此您无需再次插入它。使用以下行编辑 manage.py(或在 shell 中运行它):

admin_role = db.session.query(Role).filter_by(name='Admin').first()
user_test = User(username='test_user', role_id=admin_role.id)
db.session.add(user_test)
db.session.commit()

关于python Flask SQLAlchemy 将数据插入 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51037625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com