#刪除user表中的所有數據,表中的自增字段又從默認值開始 session.execute("truncate table user")
mysql語句查看表結構詳細信息
desc table_name 語句:
如:(查看person表的結構)
desc person; +-------+------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(8) | YES | MUL | NULL | | +-------+------------+------+-----+---------+----------------+
sqlalchemy 模型與表的映射
class Article(db.Model): __tablename__='article' id=db.Column(db.Integer,primary_key=True,autoincrement=True) title=db.Column(db.String(100),nullable=False) content=db.Column(db.Text,nullable=False) db.create_all()
+---------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(100) | NO | | NULL | |
| content | text | NO | | NULL | |
+---------+--------------+------+-----+---------+----------------+
### FLask -SQLALchemy數據的增、刪、改、查:
1.增:
#增加:
article1 = Article(title=' aaa' , content= ' bbb')
db. session. add(article1)
#事務
db. session. commit()
2.查:
# select * from article where article.title='aaa' ;
article1 = Article. query. filter(Article.title == 'aaa').first()
print (article1. title)
3.改:
# 1.先把你要更改的數據查找出來
article1 = Article. query. filter(Article.title == 'aaa'). first()
# 2.把這條數據,你需要修改的地方進行修改
article1.title = 'new title '
# 3.做事務的提交
db. session. commit( )
4.刪:
# 1.把需要刪除的數據查找出來
article1 = Article. query. filter(Article.content == 'bbb'). first()
# 2.把這條數據刪除掉
db. session. delete(article1)
# 3.做事務提交
db. session. commit( )
### Flask- SQLALchemy外鍵及其關系:
1.外鍵:
class User(db. Model): __tablename__ ='user' id = db.Column(db.Integer, primary_ key=True, autoincrement=True) username = db.Column(db.String(100) ,nullable=False) class Article( db.Model): __tablename__ ='article' id = db.Column( db.Integer, primary_ key=True, autoincrement=True) title = db.Column(db.String(100) , nullable=False) content = db.Column(db.Text, nullable=False) author_id = db.Column(db.Integer, db.ForeignKey('user.id') author = db.relationship( 'User' , backref=db.backref( 'articles'))
2. author = db. relationship( 'User', backref=db. backref('articles'))
解釋:
* 給'Article'這個模型添加一個'author'屬性,可以訪問這篇文章的作者的數據,像訪問普通模型一樣。
* 'backref'是定義反向引用,可以通過'User.articles'訪問這個模型所寫的所有文章。