当前位置:   article > 正文

网页开发:MySQL和Python案例_mysql网页

mysql网页

目录

一、MySQL的概念和引入

二、MySQL指令

1、数据库管理(文件夹)

2、数据表的管理(文件)

3、数据行操作

 三、常用的数据类型

四、员工管理案例

1、使用MySQL内置工具(命令)

 2、Python代码实现

①创建数据

② 动态创建数据

③查询数据

④删除数据

⑤修改数据

五、案例:Flask+MySQL

1、新增用户

2、查询用户


一、MySQL的概念和引入

  • Python相关:基础、函数、数据类型、面向、模块。
  • 前端开发:HTML、CSS、JavaScript、jQuery【静态页面】

Java+前端 ; Python+前端 ; Go+前端   ->【动态页面】

 直观:

  • 静态页面 = 写死了,页面永远长一个样子。
  • 动态页面 = 页面上的数据可以实时修改和展示。

动态:需要Web框架的功能

 简单的Flask网页

  1. from flask import Flask, render_template
  2. app = Flask(__name__)
  3. @app.route('/index')
  4. def index():
  5. # 目前写死:读取文件
  6. users = ["派大星", "海绵宝宝", "章鱼哥"]
  7. # 1.找到index.html的文件,读取所有内容
  8. # 2.找到内容中‘特殊的占位符’,将数据替换
  9. # 3.将替换完成的字符串返还给用户的浏览器
  10. return render_template("index.html", title="派大星",data_list = users)
  11. if __name__ == '__main__':
  12. app.run()
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <link href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
  7. </head>
  8. <body>
  9. <nav class="navbar navbar-default">
  10. <div class="container-fluid">
  11. <div class="navbar-header">
  12. <a class="navbar-brand" href="#">
  13. <img alt="Brand" src="/static/img/img.png">
  14. </a>
  15. </div>
  16. </div>
  17. </nav>
  18. <div class="container">
  19. <h3>{{title}}</h3>
  20. <table class="table table-bordered">
  21. <caption>Optional table caption.</caption>
  22. <thead>
  23. <tr>
  24. <th>#</th>
  25. <th>First Name</th>
  26. <th>Last Name</th>
  27. <th>Username</th>
  28. </tr>
  29. </thead>
  30. <tbody>
  31. {% for item in data_list %}
  32. <tr>
  33. <th scope="row">1</th>
  34. <td>{{item}}</td>
  35. <td>Otto</td>
  36. <td>@mdo</td>
  37. </tr>
  38. {% endfor %}
  39. </tbody>
  40. </table>
  41. </div>
  42. <script src="static/js/jQuery.js"></script>
  43. <script src="static/plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
  44. </body>
  45. </html>

 对于目前的我们来看,什么可以做数据的存储:

  • txt文件
  • excel文件
  • 存储数据地方(专业的软件):数据库管理系统。

MySQL/Oracke/SQLServer/DB2/Access...

二、MySQL指令

在MySQL和我们平时认知不同的概念

MySQL认知
数据库文件夹
数据表文件(EXCEL文件)

1、数据库管理(文件夹)

  • 查看已有的数据库(文件夹)
show databases;
  •  创建数据库(文件夹)
create database 数据库名字 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  • 删除数据库(文件夹)
drop database 数据库名字;
  • 进入数据库(进入文件夹)
use 数据库名称;

2、数据表的管理(文件)

  •  查看文件夹下所有的数据表(文件)
show tables;
  • 创建表
  1. create table 表名称(
  2. 列名称 类型,
  3. 列名称 类型,
  4. 列名称 类型
  5. ) default charset=utf8;
  1. create table tb1(
  2. id int, -- 允许为空(默认)
  3. name varchar(16) not null, -- 不允许为空
  4. age int default 3 -- 插入数据时,age列的默认值为3
  5. ) default charset=utf8;

  1. create table tb1(
  2. id int primary key, --主键(不允许为空,不允许重复)
  3. name varchar(16),
  4. age int
  5. ) default charset=utf8;

主键一般用于表示当前的数据的编号(类似于人的身份证号)

  1. create table tb1(
  2. id int auto_increment primary key, --内部维护,自增
  3. name varchar(16),
  4. age int
  5. ) default charset=utf8;

一般情况下创建表的时候都是这么来写:

  1. create table tb1(
  2. id int not null auto_increment primary key,
  3. name varchar(16),
  4. age int
  5. ) default charset=utf8;
  • 删除表
drop table 表名称;

3、数据行操作

  • 新增数据 
  1. insert into 表名称(字段1, 字段2, ...) values(1, "张三", ...);
  2. example
  3. insert into tb1(name,age) values("张三",25);
  •  查询数据
  1. select 字段名(或者*) from 表名称;
  2. select 字段名(或者*) from 表名称 where 条件;
  1. mysql> select * from tb1;
  2. +----+--------+------+
  3. | id | name | age |
  4. +----+--------+------+
  5. | 1 | 张三 | 25 |
  6. +----+--------+------+
  7. mysql> select name from tb1;
  8. +--------+
  9. | name |
  10. +--------+
  11. | 张三 |
  12. +--------+
  13. mysql> select * from tb1 where id = 1;
  14. +----+--------+------+
  15. | id | name | age |
  16. +----+--------+------+
  17. | 1 | 张三 | 25 |
  18. +----+--------+------+
  • 删除数据
  1. delete from 表名称; --删除所有数据
  2. delete from 表名称 where 条件; --删除指定数据
  1. delete from tb1 where id = 1;
  2. delete from tb1 where id = 1 and name = "张三";
  3. delete from tb1 where id = 1 or id = 100;
  4. delete from tb1 where id > 100;
  5. delete from tb1 where id != 50;
  6. delete from tb1 where id in (10,15);
  • 修改数据
  1. update 表名称 set= 值; --修改一列
  2. update 表名称 set= 值, 列 = 值; --修改多列
  3. update 表名称 set=where 条件; --修改某行某列
  1. update tb1 set name="李四" where id = 1;
  2. update tb1 set age=age+10 where name=""李四;

 三、常用的数据类型

  • int

有符号, 取值范围: -2147483648 ~ 2147483647(有正有负)
无符号, 取值范围: 0 ~ 4294967295(只有正)  【默认】

  • tinyint

有符号, 取值范围: -128 ~ 127(有正有负)
无符号, 取值范围: 0 ~ 255(只有正)

  1. create table tb2(
  2. id int not null auto_increment primary key,
  3. age tinyint --有符号, 取值范围: -128 ~ 127
  4. ) default charset=utf8;
  1. create table tb1(
  2. id int not null auto_increment primary key,
  3. age tinyint unsigned --无符号, 取值范围: 0 ~ 255
  4. ) default charset=utf8;
  • bigint

有符号, 取值范围: -9223372036854775808 ~ 9223372036854775807(有正有负)
无符号, 取值范围: 0 ~ 18446744073709551615(只有正)

练习

  1. # 创建表
  2. create table tb2(
  3. id bigint not null auto_increment primary key,
  4. salary int,
  5. age tinyint
  6. ) default charset=utf8;
  7. # 插入数据
  8. insert into tb2(salary,age)values(10000,18);
  9. insert into tb2(salary,age)values(20000,28);
  10. insert into tb2(salary,age)values(30000,38),(40000,40);
  11. # 查看表中的数据
  12. select * from tb2;

  •  float
  • double
  • decimal

准确的小数值,m是数字总个数(负号不算),d是小数点后个数,m最大值为65,d的最大值为30

  1. create table tb1(
  2. id int auto_increment primary key, --内部维护,自增
  3. name varchar(16),
  4. salary decimal(8,2) --一共8位(整数位数+小数点位数), 保留小数点后2位
  5. ) default charset=utf8;
  • char

定长字符串, 默认固定用 11 个字符串进行存储,哪怕字符串个数不足,也按照11个字符存储
最多能存储255个字节的数据
查询效率高

  • varchar

变长字符串,默认最长 11 个字符,真实数据多长就按多长存储
最多能存储 65535 个字节的数据,中文可存储 65535/3 个汉字
相对 char 类型,查询效率低

  • text

保存变长的大字符串,可以最多到 65535 个字符
一般用于文章和新闻

  • mediumtext
  • longtext
  • datatime

YYYY-MM-DD HH:MM:SS (1000-01-01 00:00:00/9999-12-31 23:59:59)

  • data

YYYY-MM-DD (1000-01-01/9999-12-31)

四、员工管理案例

1、使用MySQL内置工具(命令)

  1. 创建数据库:unicom
  2. 数据一张表:admin

表名:admin

列: 

  • id 整型 自增 主键
  • username: 字符串 不为空
  • password: 字符串 不为空
  • mobile: 字符串 不为空
  1. mysql> create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  2. Query OK, 1 row affected (0.00 sec)
  3. mysql> use unicom
  4. Database changed
  5. mysql> create table admin(
  6. -> id int auto_increment primary key,
  7. -> username varchar(30) not null,
  8. -> password varchar(30) not null,
  9. -> mobile varchar(20) not null)default charset=utf8;
  10. Query OK, 0 rows affected (0.02 sec)
  11. mysql> desc admin;
  12. +----------+-------------+------+-----+---------+----------------+
  13. | Field | Type | Null | Key | Default | Extra |
  14. +----------+-------------+------+-----+---------+----------------+
  15. | id | int(11) | NO | PRI | NULL | auto_increment |
  16. | username | varchar(30) | NO | | NULL | |
  17. | password | varchar(30) | NO | | NULL | |
  18. | mobile | varchar(20) | NO | | NULL | |
  19. +----------+-------------+------+-----+---------+----------------+
  20. 4 rows in set (0.00 sec)

 2、Python代码实现

安装pymysql

pip install pymysql

①创建数据

  1. import pymysql
  2. # 1.连接MySQL
  3. conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="123123", charset='utf8', db='unicom')
  4. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  5. # 2.发送指令
  6. cursor.execute("insert into admin(username, password, mobile) values('Patrickstar', '123456', '12345678912');")
  7. conn.commit()
  8. # 3.关闭
  9. cursor.close()
  10. conn.close()
  1. mysql> select * from admin;
  2. +----+-------------+----------+-------------+
  3. | id | username | password | mobile |
  4. +----+-------------+----------+-------------+
  5. | 1 | Patrickstar | 123456 | 12345678912 |
  6. +----+-------------+----------+-------------+
  7. 1 row in set (0.00 sec)

优化

  1. import pymysql
  2. # 1.连接Mysql
  3. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123123', charset='utf8', db='unicom')
  4. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  5. # 2.发送指令
  6. sql = "insert into admin(username, password, mobile) values(%s, %s, %s);"
  7. cursor.execute(sql, ['babe', '123456', '15555555555'])
  8. conn.commit()
  9. # 3.关闭
  10. cursor.close()
  11. conn.close()

注意: sql语句不要使用字符串格式化,有会SQL注入的风险,需要使用 cursor.execute(sql, [参数1, 参数2, …])

② 动态创建数据

  1. import pymysql
  2. while True:
  3. user = input("用户名:")
  4. if user.upper() == 'Q':
  5. break
  6. pwd = input("密码:")
  7. mobile = input("手机号:")
  8. # 1.连接Mysql
  9. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123123', charset='utf8', db='unicom')
  10. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  11. # 2.发送指令
  12. sql = "insert into admin(username, password, mobile) values(%s, %s, %s);"
  13. cursor.execute(sql, [user, pwd, mobile])
  14. conn.commit()
  15. # 3.关闭
  16. cursor.close()
  17. conn.close()

③查询数据

  1. #!/usr/bin/env python3
  2. import pymysql
  3. # 1.连接Mysql
  4. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
  5. passwd='123123', charset='utf8', db='unicom')
  6. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  7. # 2.发送指令
  8. sql = "select * from admin where id > %s"
  9. cursor.execute(sql, [2, ])
  10. # data_list = cursor.fetchall() 查询一条数据,为字典
  11. data_list = cursor.fetchall()
  12. # 查询所有符合条件的数据,为列表套多个字典
  13. for row_dict in data_list:
  14. print(row_dict)
  15. # 3.关闭
  16. cursor.close()
  17. conn.close()

④删除数据

  1. #!/usr/bin/env python3
  2. import pymysql
  3. # 1.连接Mysql
  4. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
  5. passwd='123123', charset='utf8', db='unicom')
  6. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  7. # 2.发送指令
  8. sql = "delete from admin where id > %s"
  9. cursor.execute(sql, [3, ])
  10. conn.commit()
  11. # 3.关闭
  12. cursor.close()
  13. conn.close()

⑤修改数据

  1. #!/usr/bin/env python3
  2. import pymysql
  3. # 1.连接Mysql
  4. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
  5. passwd='123123', charset='utf8', db='unicom')
  6. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  7. # 2.发送指令
  8. sql = "update admin set mobile=%s where id = %s"
  9. cursor.execute(sql, ['12332145665', 3])
  10. conn.commit()
  11. # 3.关闭
  12. cursor.close()
  13. conn.close()

五、案例:Flask+MySQL

1、新增用户

html文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. </head>
  7. <body>
  8. <h1>添加用户</h1>
  9. <form method="post" action="/add/user">
  10. <input type="text" name="user" placeholder="用户名">
  11. <input type="text" name="pwd" placeholder="密码">
  12. <input type="text" name="mobile" placeholder="手机号">
  13. <input type="submit" value="提 交">
  14. </form>
  15. </body>
  16. </html>

app.py

  1. from flask import Flask, render_template, request
  2. import pymysql
  3. app = Flask(__name__)
  4. @app.route("/add/user", methods=["GET", "POST"])
  5. def add_user():
  6. if request.method == "GET":
  7. return render_template("add_user.html")
  8. username = request.form.get("user")
  9. password = request.form.get("pwd")
  10. mobile = request.form.get("mobile")
  11. # 1.连接MySQL
  12. conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="123123", charset='utf8', db='unicom')
  13. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  14. # 2.发送指令
  15. sql = "insert into admin(username, password, mobile) values(%s, %s, %s);"
  16. cursor.execute(sql, [username, password, mobile])
  17. conn.commit()
  18. # 3.关闭
  19. cursor.close()
  20. conn.close()
  21. return "添加成功"
  22. if __name__ == '__main__':
  23. app.run()

2、查询用户

html文件

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. </head>
  7. <body>
  8. <h1>用户列表</h1>
  9. <table border="1">
  10. <thead>
  11. <tr>
  12. <th>ID</th>
  13. <th>姓名</th>
  14. <th>密码</th>
  15. <th>手机号</th>
  16. </tr>
  17. </thead>
  18. <tbody>
  19. {% for item in data_list %}
  20. <tr>
  21. <td>{{ item.id }}</td>
  22. <td>{{ item.username }}</td>
  23. <td>{{ item.password }}</td>
  24. <td>{{ item.mobile }}</td>
  25. </tr>
  26. {% endfor %}
  27. </tbody>
  28. </table>
  29. </body>
  30. </html>

app.py

  1. from flask import Flask, render_template, request
  2. import pymysql
  3. app = Flask(__name__)
  4. @app.route("/add/user", methods=["GET", "POST"])
  5. def add_user():
  6. if request.method == "GET":
  7. return render_template("add_user.html")
  8. username = request.form.get("user")
  9. password = request.form.get("pwd")
  10. mobile = request.form.get("mobile")
  11. # 1.连接MySQL
  12. conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password="123123", charset='utf8', db='unicom')
  13. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  14. # 2.发送指令
  15. sql = "insert into admin(username, password, mobile) values(%s, %s, %s);"
  16. cursor.execute(sql, [username, password, mobile])
  17. conn.commit()
  18. # 3.关闭
  19. cursor.close()
  20. conn.close()
  21. return "添加成功"
  22. @app.route("/show/user", methods=['GET', 'POST'])
  23. def show_user():
  24. username = request.form.get('user')
  25. password = request.form.get('pwd')
  26. mobile = request.form.get('mobile')
  27. # 1.连接Mysql
  28. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='123123', charset='utf8', db='unicom')
  29. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  30. # 2.发送指令
  31. sql = "select * from admin"
  32. cursor.execute(sql)
  33. data_list = cursor.fetchall()
  34. # 3.关闭
  35. cursor.close()
  36. conn.close()
  37. return render_template("show_user.html", data_list=data_list)
  38. if __name__ == '__main__':
  39. app.run()

 优化之后

加入 bootstrap.css

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. <link rel="stylesheet" href="../static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <h1>用户列表</h1>
  11. <table class="table table-bordered">
  12. <thead>
  13. <tr>
  14. <th>ID</th>
  15. <th>姓名</th>
  16. <th>密码</th>
  17. <th>手机号</th>
  18. </tr>
  19. </thead>
  20. <tbody>
  21. {% for item in data_list %}
  22. <tr>
  23. <td>{{ item.id }}</td>
  24. <td>{{ item.username }}</td>
  25. <td>{{ item.password }}</td>
  26. <td>{{ item.mobile }}</td>
  27. </tr>
  28. {% endfor %}
  29. </tbody>
  30. </table>
  31. </div>
  32. </body>
  33. </html>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/432213
推荐阅读
相关标签
  

闽ICP备14008679号