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().

猜你喜欢

转载自blog.csdn.net/BSCHN123/article/details/121307299