博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
flask_sqlalchemy的使用
阅读量:6615 次
发布时间:2019-06-24

本文共 1239 字,大约阅读时间需要 4 分钟。

 

  • 第一配置文件

# coding:utf-8DIALECT = 'mysql'DRIVER = 'pymysql'USERNAME = 'root'PASSWORD = '123456'HOST = '127.0.0.1'PORT = '3306'DATABASE = 'student'SQLALCHEMY_DATABASE_URI = '{}+{}://{}:{}@{}:{}/{}?charset=utf8'.format(    DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE)SQLALCHEMY_COMMIT_ON_TEARDOWN = TrueSQLALCHEMY_TRACK_MODIFICATIONS = True
  • 链接数据库进行创建表
# coding:utf-8from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__,template_folder='templates')# ['SQLALCHEMY_DATABASE_URL'] = 'mysql+mysqlconnector://root:123456@localhost:3306/student'''app.config.from_object('config')db = SQLAlchemy(app)class user_database(db.Model):    id = db.Column(db.INT,primary_key=True)    name = db.Column(db.String(255),unique=False)    sex  = db.Column(db.String(10),unique=False)    def __init__(self,id,name,sex):        self.id = id        self.name = name        self.sex = sex# 创建数据库db.create_all()db.session.commit()# 实例化插入数据库text_1 = user_database(1,'八戒','男')# db.session.add(user_database(2,'猴哥','man'))# db.session.add(user_database(3,'物镜','man'))# db.session.add(user_database(4,'师父','man'))db.session.add(user_database(5,'李大郎','man'))db.session.commit()

 

转载于:https://www.cnblogs.com/wwthuanyu/p/10071376.html

你可能感兴趣的文章