# coding=utf-8
from flask import Flask
import pymysql
from flask import request
import json
app = Flask(__name__)
@app.route('/add', methods=['get', 'post'])
def add():
if request.method == 'GET':
name1 = request.values.get('name')
age1 = request.values.get('age')
elif request.method == 'POST':
try:
name1 = request.form['name']
age1 = request.form['age']
except KeyError:
ret = {'code': 10001, 'message': '参数不能为空!'}
return json.dumps(ret, ensure_ascii=False)
if name1 and age1:
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# sql插入语句 拼接注意字符串要加引号
sql = "insert into person(name,age) values ('" + name1 + "' ," + age1 + ")"
print(sql)
try:
cursor.execute(sql)
# 提交
db.commit()
return '添加成功'
except Exception as e:
# 错误回滚
db.rollback()
return '添加失败'
finally:
db.close()
@app.route('/delete', methods=['get', 'post'])
def delete():
if request.method == 'GET':
id1 = request.values.get('id')
elif request.method == 'POST':
try:
id1 = request.form['id']
except KeyError:
ret = {'code': 10001, 'message': '参数不能为空!'}
return json.dumps(ret, ensure_ascii=False)
if id1:
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# sql删除语句
sql = "delete from person where id =" + id1
try:
cursor.execute(sql)
# 提交
db.commit()
return '删除成功'
except Exception as e:
# 错误回滚
db.rollback()
return '删除失败'
finally:
db.close()
@app.route('/modify', methods=['get', 'post'])
def modify():
if request.method == 'GET':
id1 = request.values.get('id')
name1 = request.values.get('name')
age1 = request.values.get('age')
elif request.method == 'POST':
try:
id1 = request.form['id']
name1 = request.values.get('name')
age1 = request.values.get('age')
except KeyError:
ret = {'code': 10001, 'message': '参数不能为空!'}
return json.dumps(ret, ensure_ascii=False)
if id1 and name1 and age1:
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# sql修改语句
sql = "update person set age =" + age1 + ", name = '" + name1 + "'where id = " + id1
try:
cursor.execute(sql)
# 提交
db.commit()
return '修改成功'
except Exception as e:
# 错误回滚
db.rollback()
return '修改失败'
finally:
db.close()
@app.route('/query', methods=['get', 'post'])
def query():
if request.method == 'GET':
id1 = request.values.get('id')
elif request.method == 'POST':
try:
id1 = request.form['id']
except KeyError:
ret = {'code': 10001, 'message': '参数不能为空!'}
return json.dumps(ret, ensure_ascii=False)
if id1:
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test")
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()
# sql查询语句
sql = "select * from person where id = " + id1
try:
cursor.execute(sql)
# 提交
db.commit()
results = cursor.fetchall()
# 遍历结果
for rows in results:
id1 = rows[0]
name1 = rows[1]
age1 = rows[2]
print("id=%s,name=%s,age=%s" % (id1, name1, age1))
return "查询成功"
except Exception as e:
# 错误回滚
db.rollback()
return '查询失败'
finally:
db.close()
# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
# 指定端口和ip
app.run(debug=True, host='0.0.0.0', port=8010)
可直接复制修改后缀名
{
"info": {
"_postman_id": "df502980-2983-482c-9b18-5bbdb13fd605",
"name": "Flask",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "添加",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8010/add?name=张三&age=22",
"protocol": "http",
"host": [
"localhost"
],
"port": "8010",
"path": [
"add"
],
"query": [
{
"key": "name",
"value": "张三"
},
{
"key": "age",
"value": "22"
}
]
},
"description": "添加"
},
"response": []
},
{
"name": "删除",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8010/delete?id=6",
"protocol": "http",
"host": [
"localhost"
],
"port": "8010",
"path": [
"delete"
],
"query": [
{
"key": "id",
"value": "6"
}
]
}
},
"response": []
},
{
"name": "修改",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8010/modify?id=1&name=张三&age=23",
"protocol": "http",
"host": [
"localhost"
],
"port": "8010",
"path": [
"modify"
],
"query": [
{
"key": "id",
"value": "1"
},
{
"key": "name",
"value": "张三"
},
{
"key": "age",
"value": "23"
}
]
}
},
"response": []
},
{
"name": "查询",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:8010/query?id=1",
"protocol": "http",
"host": [
"localhost"
],
"port": "8010",
"path": [
"query"
],
"query": [
{
"key": "id",
"value": "1"
}
]
}
},
"response": []
}
]
}
/*
Navicat MySQL Data Transfer
Source Server : localhost_3306
Source Server Version : 80012
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 80012
File Encoding : 65001
Date: 2021-06-10 11:32:01
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`name` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(3) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
三个文件打包在资源区,名为:Flask+mysql+postman.rar