python SQLAlchemy的简单配置和查询
背景:
今天小鱼从0开始配置了下 SQLAlchemy 的连接方式,并查询到了结果,记录下来
需要操作四个地方
1. config ------数据库地址
2.init ----- 数据库初始化
3.model ----- 数据库表模型
4.增删改查
1.config
1 SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://username:/dbname?charset=utf8‘
2. init
from flask import Flask from flask_sqlalchemy import SQLAlchemy from xxxx import config #导入1中的配置 app = Flask(__name__) app.config.from_object(config) db = SQLAlchemy(app)
3.model
from xxxx import db #从2中导入db class TableName(db.Model): __tablename__ = ‘tablename‘ id = db.Column(db.Integer, primary_key=True) name= db.Column(db.String(100)) datetime = db.Column(db.DateTime) def __repr__(self): return ‘<TableName%r>‘ % self.id
4.查询
from xxx.model import TableName #从三中导入 result = TableName.query print(result )#返回sql语句 print(result.first()) #查询第一条 print(result.all()) # 查询所有 print(result.first().id) #查询第一条 id值
其他增删改查 语句可查询相关文档,如:
相关推荐
liuweiq 2020-06-14
emmm00 2020-06-14
lt云飞扬gt 2020-05-29
朱建伟 2020-05-14
猛禽的编程艺术 2020-05-06
苦咖啡flask 2020-05-04
dreamhua 2020-04-30
dreamhua 2020-04-30
tanrong 2020-04-30
xuanlvhaoshao 2020-04-26
tanrong 2020-04-18
Danialzhou 2020-04-11
happinessaflower 2020-03-01
xiaoxiangyu 2020-02-23
喝绿茶的猫 2020-01-18
疯狂老司机 2020-01-10
liuyang000 2020-01-08
Lingforme 2020-01-08