栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Create records in python‘s interactive mode using

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Create records in python‘s interactive mode using

db.session.add()
There is another way of inserting records into our database, rather than entering a client like psql and using INSERT INTO SQL commands; we can call db.session from SQLAlchemy to create records using instances of our defined SQLAlchemy models.

In interactive mode, import db and your Person model. (这里说的Person是数据库的名字)

$ cd YOUR_PROJECT_DIRECTORY
$ python3
>>> from flask_example import db, Person

Then, create an instance of a Person, setting its attributes, and setting it equal to a variable person.

>>> person = Person(name='Amy')

We are going to call db.session.add(), a method on the Session interface in SQLAlchemy, to add this object to a session.

>>> db.session.add(person)

This will queue up a INSERT INTO persons (name) VALUES (‘Amy’); statement in a transaction that is managed by db.session.

We. can then call db.session.commit()

>>> db.session.commit()

and that person record will now exist in our persons table, within our database. You can double-check this is in psql by running SELECt * from persons; command from psql.

In summary
We can insert new records into the database using SQLAlchemy by running

person = Person(name='Amy')
db.session.add(person)
db.seesion.commit()

which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit().

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/488227.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号