python SQLAlchemy's simple to configure and query

background:

Today fish from 0 to configure the connection under SQLAlchemy and queries to the results recorded

 

Need to operate four places

1. config ------ database address

2.init ----- database initialization

3.model ----- database table model

4. CRUD

 

1.config

1 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://username:[email protected]/dbname?charset=utf8'

 

2. init

1 from flask import Flask
2 from flask_sqlalchemy import SQLAlchemy
3 from xxxx import config #导入1中的配置
4 
5 app = Flask(__name__)
6 app.config.from_object(config)
7 db = SQLAlchemy(app)

 

3.model 

 1 from xxxx import db  #从2中导入db
 2 
 3 class TableName(db.Model):
 4     __tablename__ = 'tablename'
 5 
 6     id = db.Column(db.Integer, primary_key=True)
 7     name= db.Column(db.String(100))
 8     datetime = db.Column(db.DateTime)
 9 
10     def __repr__(self):
11         return '<TableName%r>' % self.id

 

4. Query

. 1  from xxx.model Import the TableName # imported from the three
 2  
. 3 Result = TableName.query  
 . 4  Print (Result) # Returns sql statement 
. 5  
. 6  Print (result.first ()) # query first 
. 7  Print (result.all ( ))   # query all 
8  Print (result.first (). id) # inquiry Article id value

 

Other CRUD statement relevant documents, such as:

https://www.cnblogs.com/zhangju/p/5720210.html

 

 

Guess you like

Origin www.cnblogs.com/whycai/p/11963443.html