Flask框架连接mysql数据库

1.安装mysql

下载安装包进行安装,可以参考  安装mysql

安装完成后修改密码

2.登录数据库

进入到安装目录bin下,打开cmd窗口

在cmd出口中输入命令
mysql -u root -p

如果无法连接到服务器,则启动mysql服务

 鼠标右键我的电脑-管理-服务,选择mysql,右键启动

Flask框架连接mysql数据库_第1张图片

Flask框架连接mysql数据库_第2张图片

 启动后再次输入用户密码,连接成功Flask框架连接mysql数据库_第3张图片

创建数据库

#创建数据库
create database dlz default charset utf8;

#查询数据库
show databases;

Flask框架连接mysql数据库_第4张图片

查询表

use dlz;
show tables;

Flask框架连接mysql数据库_第5张图片

查看表结构

#查看表结构
desc dlz;
#查询表中记录
select * from dlz;

Flask框架连接mysql数据库_第6张图片

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql
pymysql.install_as_MySQLdb()

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:密码@127.0.0.1:3306/dlz'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200))
    ps = db.Column(db.String(200))

    def __repr__(self):
        return "{},{},{}".format(self.id, self.name, self.ps)


if __name__ == '__main__':
    db.drop_all()
    db.create_all()
    role1 = Role(name='zhangsan',ps='44')
    db.session.add(role1)
    db.session.commit()
    a=Role.query.get(1)
    print(a)
from datetime import timedelta

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
# 配置数据库地址
# alter user user() identified by "Aa123456";
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:密码@127.0.0.1:3306/dlz'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


@app.route('/')
def index():
    url_str = 'www.dlz.com。3333'
    my_list = ['2', 5]
    # 查询作者数据传给模板
    authors = Author.query.all()
    return render_template('dlz.html', url_str=url_str, my_list=my_list, authors=authors)
    # return '333333'


class Author(db.Model):
    # 表名
    __tablename__ = 'authors'
    # 字段
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(16), unique=True)
    # 关系引用
    # books是给Author模型引用的,author是给Book引用的
    books = db.relationship('Book', backref='author')

    def __repr__(self):
        # 重写repr方法
        return "{}:{}".format(self.id, self.name)


# 定义书籍模型
class Book(db.Model):
    __tablename__ = 'books'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), unique=True)
    author_id = db.Column(db.Integer, db.ForeignKey('authors.id'))

    def __repr__(self):
        return "{}:{}".format(self.id, self.name)


if __name__ == '__main__':
    # app.debug = True
    # app.run()
    db.drop_all()
    db.create_all()
    role1 = Author(name='zhangsan')
    role2 = Author(name='lisi')
    book1 = Book(name='11111')
    book2 = Book(name='22222')
    db.session.add_all([role1, role2, book1, book2])
    db.session.commit()
    app.run(debug=True)
环境配置如下
(venv) D:\python\20211106>pip list
Package            Version
------------------ --------
click              8.0.3
colorama           0.4.4
dataclasses        0.8
Flask              1.1.2
Flask-MySQLdb      0.2.0
Flask-SQLAlchemy   2.4.0
greenlet           1.1.2
importlib-metadata 4.8.1
itsdangerous       2.0.1
Jinja2             3.0.2
MarkupSafe         2.0.1
mysql              0.0.3
mysqlclient        2.0.3
pip                21.3.1
setuptools         58.5.3
SQLAlchemy         1.3.0
typing-extensions  3.10.0.2
Werkzeug           2.0.2
zipp               3.6.0

你可能感兴趣的:(测试,flask,mysql,数据库)