flask中使用mysql导入数据

1.首先创建一个表

import pymysql
# 连接数据库
connect = pymysql.connect(host='127.0.0.1', user='root', password='')
cursor = connect.cursor() #创建一个游标,类似于一个帮助我们执行命令的工具

cursor.execute("use day01db") # 选择一个你保存的数据库
sql = """
create table books(
id int not null primary key auto_increment,
name varchar(128),
price int not null
)default charset=utf8; #不能写utf-8
""" #写mysql命令

cursor.execute(sql)
connect.commit() #提交内容

2.向表中填写内容

cursor.execute("insert into books(name,price) values('十四行诗','14')")
cursor.execute("insert into books(name,price) values('浮士德','20')")
cursor.execute("insert into books(name,price) values('平凡的世界','17')")
connect.commit()

这时候我们可以使用select * from books查看内容是否插入

cursor.execute('use day01db')
cursor.execute('show tables')
cursor.execute('select * from books')
resp = cursor.fetchall()

print(resp)

3.这是时候我们就可以导入flask框架了

#获取数据库的内容
from flask import Flask, render_template, redirect, request
import pymysql
connect = pymysql.connect(host='127.0.0.1', user='root', password='')
cursor = connect.cursor()
cursor.execute('use day01db')
cursor.execute('show tables')
cursor.execute('select * from books')
resp = cursor.fetchall()
cursor.close()
connect.close()

4.在html中输出

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <table border="1">
        <thead>
        <tr>
            <td>ID</td>
            <td>书名</td>
            <td>价格</td>
            <td>操作</td>
        </tr>
        </thead>
        <tbody>
        {% for i in data %}
        <tr>
            <td>{{i[0]}}</td>
            <td>{{i[1]}}</td>
            <td>{{i[2]}}</td>
            <td>
                <a href="/edit?nid={{i[0]}}">修改</a>
                <a href="/dele?nid={{i[0]}}">删除</a>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</body>
</html>

效果如下
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值