Write SQLAlchemy Database today
First, we introduce the concept of ORM:
Orm,object class, Relationship: Relationship, Mapping: mapping, i.e. model relational mapping
Flask-sqlalchemy is a set of ORM frameworks
The benefits of ORM: It is very convenient for us to manipulate the database as it is to manipulate objects, because a table is abstracted into a class, and a piece of data is abstracted into an object of that class.
Use of # # # Flask-sqlalchemy:
1. Initialize and set database configuration information:
* Initialize with SQLAlchemy in Flask_sqlalchemy:
```
From Flask_sqlalchemy import SQLAlchemy
App = Flask (__name__)
db = SQLAlchemy (APP)
```
2. Set configuration information: Add the following configuration information to the ' config.py ' file:
```
# Dialect+driver://username:[email protected]:p ort/database
dialect = ' database type '
DRIVER = ' Pymysql ' (python2.7 is MySQLdb)
USERNAME = ' User name '
PASSWORD = ' Password '
HOST = ' 127.0.0.1 '
PORT = ' 3306 '
Database = ' db name '
Sqlalchemy_database_uri = "{}+{}://{}:{}@{}:{}/{}?charset=utf8". Format (dialect,driver,username,password,host
, Port,database)
Sqlalchemy_track_modifications = False
```
3. In the main ' app ' file, add the configuration file:
```
App = Flask (__name__)
App.config.from_object (config)
db = SQLAlchemy (APP)
```
4. Do a test to see if there is a problem:
```
Db.create_all ()
```
If there is no error, the configuration is not a problem, if there are errors, can be modified according to the error.
# # # Use Flask-sqlalchemy to create a mapping of the model to the table:
1. The model needs to inherit from ' db '. Model ', which then needs to be mapped to a property in the table, must be written as ' db '. The data type of Column '.
2. Data type:
* ' db. Integer ' stands for shaping.
* ' db. String ' represents ' varchar ' and needs to specify the longest length.
* ' db. Text ' stands for ' text '.
3. Other parameters:
* ' Primary_key ': Represents the setting of this field as the primary key.
* ' AutoIncrement ': This represents the primary key for self-growth.
* ' Nullable ': represents whether this field can be empty, the default can be empty, you can set this value to ' False ', in the database, this value can not be empty.
4. Finally, you need to call ' db.create_all ' to actually create the model into the database.
Database additions and deletions change:
The main app file code is as follows:
fromFlaskImportFlask fromFlask_sqlalchemyImportSQLAlchemyImportConfigapp= Flask (__name__) App.config.from_object (config) DB=SQLAlchemy (APP)#Article table:#CREATE TABLE article (#ID int primary key autoincrement,#title varchar (+) is not NULL,#content text NOT NULL,# )classarticle (db. Model):__tablename__='article'ID= db. Column (db. Integer,primary_key=true,autoincrement=True) Title= db. Column (db. String (+), nullable=False) Content= db. Column (db. text,nullable=False) Db.create_all () @app. Route ('/')defHello_world ():##增加:Article1 = Article (title='AAA', content='BBB') Db.session.add (article1)#TransactionsDb.session.commit ()##查 ## SELECT * from article where title= ' AAA '; #result = Article.query.filter (Article.title = = ' aaa '). All () #article1 = result[0] #print (article1.title,article1.content) ##改: ##1. Find the data you want to change first #article1 = Article.query.filter (Article.title = = ' aaa '). First () ##2. Take this data and change it where you want it. #article1.title = ' new title ' ##3. Commit a transaction #Db.session.commit () ##删: ##1. Find out the data you need to delete #article1 = Article.query.filter (article.content = = ' BBB '). First () ##2. Erase this data. #Db.session.delete (article1) ##3. Do a transaction commit #Db.session.commit () return 'Hello world!'if __name__=='__main__': App.run ()
# # # Flask-sqlalchemy data to increase, delete, change, check:
1. Increase:
```
Increase
Article1 = article (title= ' AAA ', content= ' BBB ')
Db.session.add (Article1)
# Business
Db.session.commit ()
```
Note that the operation of the database is performed in the main view function, so the operation of the database can only be performed if the Web page is opened.
2. Check:
```
# check
# SELECT * from article where article.title= ' AAA ';
Article1 = Article.query.filter (Article.title = = ' aaa '). First ()
print ' title:%s '% article1.title
print ' content:%s '% article1.content
```
3. Change:
```
Modified
# 1. Find the data you want to change first
Article1 = Article.query.filter (Article.title = = ' aaa '). First ()
# 2. Make changes to this data where you need to modify it
Article1.title = ' new title '
# 3. Commit a transaction
Db.session.commit ()
```
4. By deleting:
```
# Delete
# 1. Find out the data you need to delete
Article1 = Article.query.filter (article.content = = ' BBB '). First ()
# 2. Get rid of this piece of data.
Db.session.delete (Article1)
# 3. Do a transaction commit
Db.session.commit ()
```
Flask Web Development Road Six