Python+Flask对MySQL数据库进行增删查改并在页面展示数据
一、python连接mysql数据库
1. 安装pymysql驱动
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
pip install pymysql
2. 数据库表测试数据
可以使用navicat也可以使用命令行,创建一张表
3. 连接数据库
import pymysql
#打开数据库连接
db = pymysql.connect(host="localhost",user="root",password="123456",database="test")
#使用cursor()方法获取操作游标
cursor = db.cursor()
#sql语句
sql = "select * from info"
try:
#执行sql语句
cursor.execute(sql)
#查询中的一个操作,获取所有记录
result = cursor.fetchall()
#打印表数据
for row in result:
id = row[0]
name = row[1]
age = row[2]
print(id,name,age)
except:
print("Error!")
#关闭数据库
db.close()
二、Flask+Python对数据库数据的操作
Flask相关知识点: