python SQLAlchemy的简单配置和查询
背景:
今天小鱼从0开始配置了下 SQLAlchemy 的连接方式,并查询到了结果,记录下来
需要操作四个地方
1. config ------数据库地址
2.init ----- 数据库初始化
3.model ----- 数据库表模型
4.增删改查
用的包:Flask-SQLAlchemy (2.1)
1.config
1 SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://tmadmin:zq@10.100.2.120/tm?charset=utf8' 2 SQLALCHEMY_COMMIT_ON_TEARDOWN = True 3 SQLALCHEMY_TRACK_MODIFICATIONS = False
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 #to_json 方便后面查询使用 11 def to_json(self): 12 dict = self.__dict__ 13 if "_sa_instance_state" in dict: 14 del dict["_sa_instance_state"] 15 return dict 16 17 def __repr__(self): 18 return '<TableName%r>' % self.id
4.查询1
1 from xxx.model import TableName #从三中导入 2 from sqlalchemy.sql import text,and_,or_,func 3 4 5 table_name = TableName() 6 7 #定义查询条件 8 sql_text = ' 1=1 and name like "%%{name}%%" 9 and id = {id}'.format(name=xx,id=xx) 10 11 #条件、排序、分组 12 res = table_name.query.filter(text(sql_text)).order_by(text("id desc")).limit(xxx).group_by(text("name")).all() 13 14 #结果展示 [{"name":"xxx","id":xxx}········] 15 data = [i.to_json() for i in res]
其他增删改查 语句可查询相关文档,如: