python-web开发[14]之MySQL

  • Python相关:基础、函数、数据类型、面向对象、模块。
  • 前端开发:HTML、CSS、JavaScript、jQuery。【静态页面】
Java+前端; Python+前端; Go+前端  -> 【动态页面】

直观:

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

1. 初识网站

  • 默认编写的静态的效果

  • 动态:需要用到Web框架的功能。
    在这里插入图片描述

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

  • txt文件

  • excel文件

  • 存储数据 的 专业的软件:数据库管理系统。

MySQL(*)免费
Oracle/SQLServer/DB2/Access ...

在这里插入图片描述

今日概要:

  • MySQL安装 & 配置
  • MySQL的启动和关闭
  • 指令(*)
  • Python第三方模块,发送指令并获取MySQL返回的结果。

2.安装MySQL

MySQL,本质上就是一个软件。

  • 8.x
  • 5.x ,课堂上 5.7.31版本。

2.1 下载

https://downloads.mysql.com/archives/community/

  • windows补丁(先安装)
  • MySQL压缩包(后安装)

2.2 安装补丁

2.3 安装

mysql-5.7.31-winx64.zip 是免安装的版本。

  • 解压zip文件
  • 将解压后的文件夹放入路径(不要有中文路径;建议解压到自己单独建立的文件。)

2.4 创建配置文件

修改配置文件中的数据库地址

2.5 初始化

  • 打开cmd/terminal终端 & 以管理员的权限去运行
  • 输入初始化的命令
"C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe"  --initialize-insecure

至此,MySQL的安装已完成。

3.启动MySQL

启动MySQL一般有两种方式:

  • 方式1: 通过终端来执行 临时启动(不建议) ,关闭终端就关闭了mysql
>>> "C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe"
  • 方式2: 通过命令行 制作成Windows服务,服务来进行关闭和开启。
    • 制作服务
"C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe" --install mysql57

在这里插入图片描述

  • 启动和关闭服务
  • 也可以在window的服务管理中点击按钮启动和关闭服务。例如:

4.连接测试

在这里插入图片描述

>>>"C:\Program Files\mysql-5.7.31-winx64\bin\mysql.exe" -h 127.0.0.1 -P 3306 -u xxx  -p xxx
>>>"C:\Program Files\mysql-5.7.31-winx64\bin\mysql.exe" -u xxx -p

如果你将 C:\Program Files\mysql-5.7.31-winx64\bin\添加到了系统环境变量。

在这里插入图片描述

>>> mysql -u xxx -p xxx

在这里插入图片描述

4.1 设置密码

set password = password('xxxxx');

4.2 查看已有的文件夹(数据库)

show databases;

4.3 退出(关闭连接)

exit;

4.4. 再连接MySQL

汇总命令:

C:\Users\Administrator>mysql -u xxx -p xx
mysql> set password = password('xxx');
mysql> show databases;
mysql> exit;
C:\Users\Administrator>mysql -u xxx -p  xxx
输入密码
mysql>exit;

疑问

  1. 张杰斌
  • 添加环境变量【错】,应该将mysql是的地址(bin地址)添加的环境变量中的pass
  • 重新打开终端
  • 输入指令(首次不需要设置密码)
  1. 张点墨

如果第一次进入需要密码,原因是:

以前自己安装过其他的MySQL,在终端运行mysql是用以前的那个工具。
  • 解决方案第一步: 确保MySQL服务已经开启
  • 解决方案第二步:直接过路径来编写
"C:\Program Files\mysql-5.7.31-winx64\bin\mysql.exe" -u xxx -p xxx
  • 解决方案第三步:检查自己的环境变量
自己环境变量里,是不是有以前的那个MySQL的路径,全部删除。
  • 记下来你要做如下事:
    • window服务,里面有没有以前安装的MySQL?
  1. gongxingyun
- 路径没问题
- 添加环境变量
- 关闭终端,重新打开终端。
  1. 郭智
- 确保,你是32位还是64位?
- 如果是64位,换成用管理员权限运行。
- 如果是32位,需要安装32位的MySQL(同曹成鑫)

5.忘记密码

step1: 默认情况下,启动MySQL时,需要用户输入账户名、密码。

step2: 修改MySQL配置,重新启动MySQL(无账号模式)
	mysql -u root -p 
	重新设置密码
	退出
	
step3: 再重新修MySQL配置文件,重新启动MySQL(需要账号的模式)
	mysql -u root -p 
	新密码
  • 停止现在MySQL服务
    在这里插入图片描述

  • 修改MySQL配置文件(以无账号模式)
    在这里插入图片描述

  • 重新启动MySQL
    在这里插入图片描述

  • 再次登录MySQL(无需密码)
    在这里插入图片描述

  • 执行命令设置密码

use mysql;

在这里插入图片描述

  • 重新修改配置文件(需要账号的模式登录)【服务停掉】

删除刚刚增加的一行命令,下次进入采用有账号模式

  • 重新启动MySQL
  • 登录时候输入新的密码即可。

小结

截止目前,MySQL的环境搭建相关的事全部搞定了。

  • 安装
  • 配置
  • 启动
  • 连接(密码、忘记密码)

以后我们再操作MySQL时:

  • 关闭和开启MySQL服务
  • 用MySQL自动工具连接MySQL并发送指令
myql -u xxx -p xxx

接下来,我们的重点:学习指令- mysql指令语句

6.MySQL指令

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

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

6.1 数据库管理(文件夹)

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

6.2 数据表的管理(文件)

  • 进入数据库(进入文件夹)
use 数据库;
use gx_day14;
  • 查看当前数据库下的所有 表(文件)
show tables;
  • 创建表(文件文件)
create table 表名称(
	列名称 类型,
    列名称 类型,
    列名称 类型
)default charset=utf8;
-- 以下是建表语句样例
create table t1(
	id int atuo_increament primary key, -- 设置自增主键(不允许为空,不允许重复)
  name varchar(16) null, -- 允许为空
  age int not null default 20 -- 不允许为空(默认状态允许为空); -- 设置默认值,如果未传入值,则用默认值进行填充
)default charset=utf8;

主键一般用于表示当前行的数据的编号(类似于人的身份证)。
一般情况下,我们再创建表时都会这样来写:【标准,如上的样例】

  • 删除表
drop table 表名称;

常用数据类型:

  • tinyint
有符号,取值范围:-128 ~ 127 (有正有负)【默认】
无符号,取值范围:0 ~ 255(只有正) [建表语句通过 unsigned进行确定]
  • int
int				表示有符号,取值范围:-2147483648 ~ 2147483647
int unsigned	表示无符号,取值范围:0 ~ 4294967295
  • bigint
有符号,取值范围:-9223372036854775808 ~ 9223372036854775807
无符号,取值范围:0  ~  18446744073709551615

练习题:

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

例如:
create table tb3(
  id int not null primary key auto_increment,
  salary decimal(8,2)
)default charset=utf8;

insert into tb3(salary) values(1.28);
insert into tb3(salary) values(5.289);
insert into tb3(salary) values(5.282);
insert into tb3(salary) values(122115.11),(1234.5);

select * from tb3;
  • char(m),速度快。
定长字符串,m代表字符串的长度,最多可容纳255个字符。

char(11),固定用11个字符串进行存储,即使真是没有11个字符,也会按照11存储。

create table tb4(
	id int not null primary key auto_increment,
	mobile char(11)
)default charset=utf8;

insert into tb4(mobile) values("151");
insert into tb4(mobile) values("15131255555");
  • varchar(m),节省空间。
变长字符串,m代表字符的长度。   最大65535字节/3 = 最大的m

varchar(11),真实数据有多少长久按照多长存储。

create table tb5(
	id int not null primary key auto_increment,
	mobile varchar(11)
)default charset=utf8;

insert into tb5(mobile) values("151");
insert into tb5(mobile) values("15131255555");
  • text
text数据类型用于保存变长的大字符串,可以组多到65535 (2**161)个字符。

一般情况下,长文本会用text类型。例如:文章、新闻等。

create table tb6(
	id int not null primary key auto_increment,
    title varchar(128),
	content text
)default charset=utf8;
  • mediumtext
A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters.
  • longtext
A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1)
  • datetime
YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59)
  • date
YYYY-MM-DD(1000-01-01/9999-12-31)

练习题:用户表

create table tb7(
	id int not null primary key auto_increment,
    name varchar(64) not null,
    password char(64) not null,
    email varchar(64) not null,
    age tinyint,
    salary decimal(10,2),
    ctime datetime
)default charset=utf8;


insert into tb7(name,password,email,age,salary,ctime) values("武沛齐","123","xx@live.com",19,1000.20,"2011-11-11 11:11:10");

insert into tb7(name,password,email,age,salary,ctime) values("张电摩","123","xx@live.com",19,1000.20,"2011-11-11 11:11:10");

insert into tb7(name,password,email,age,salary,ctime) values("庞小青","123","xx@live.com",19,1000.20,"2011-11-11 11:11:10");

insert into tb7(name,password,email,age,salary,ctime) values("谢涛","123","xx@live.com",19,1000.20,"2011-11-11 11:11:10");

insert into tb7(name,password,email,age,salary,ctime) values("谢鹏","123","xx@live.com",19,1000.20,"2011-11-11 11:11:10");

select * from tb7;


+----+-----------+----------+-------------+------+---------+---------------------+
| id | name      | password | email       | age  | salary  | ctime               |
+----+-----------+----------+-------------+------+---------+---------------------+
|  1 | 武沛齐    | 123      | xx@live.com |   19 | 1000.20 | 2011-11-11 11:11:10 |
+----+-----------+----------+-------------+------+---------+---------------------+
1 row in set (0.00 sec)

MySQL还有很多其他的数据类型,例如:set、enum、TinyBlob、Blob、MediumBlob、LongBlob 等,详细见官方文档:https://dev.mysql.com/doc/refman/5.7/en/data-types.html
我们平时开发系统时,一般情况下:

  • 创建数据库
  • 创建表结构

都是需要提前通过上述命令创建。

6.3 数据行操作

1. 新增数据
insert into 表名(列名,列名) values(,);
insert into 表名(列名,列名) values(,),(,),(,),(,);

2.删除数据
delete from 表名;
delete from 表名 where 条件;
delete from tb7;
delete from tb7 where id = 3;
delete from tb7 where id = 4 and name="谢涛";
delete from tb7 where id = 4 or name="谢涛";
delete from tb7 where id > 4;
delete from tb7 where id >= 4;
delete from tb7 where id != 4;
delete from tb7 where id in (1,5);

3.修改数据
update 表名 set=;
update 表名 set=,=;
update 表名 set=where 条件;
update tb7 set password="xxx";
update tb7 set email="xxx" where id > 5;

update tb7 set age=age+10 where id > 5;

f

4.查询数据
select * from 表名称;
select 列名称,列名称 from 表名称;

select 列名称,列名称 from 表名称 where 条件;
select * from tb7;
select id,name from tb7;
select id,name from tb7 where id > 10;
select id,name from tb7 where name="xx" and password="xx";

小结

我们平时开发系统时,一般情况下:

  • 创建数据库
  • 创建表结构

都是需要提前通过工具+命令创建。
但是,表中的数据一般情况下都是通过程序(或sql 或python)来实现增删改查。

7.案例:员工管理

  • 使用MySQL内置工具(命令)
    • 创建数据库:unicom
    • 数据一张表:admin
-- 表名:admin
-- 列:
-- id,整型,自增,主键。
-- username 字符串 不为空,
-- password 字符串 不为空,
-- mobile 字符串 不为空
create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
create table admin(
	id int not null primary key auto_increment,
  username varchar(64) not null,
  password varchar(64) not null,
  mobile varchar(11) not null
)default charset=utf8;
  • Python代码实现:
    • 添加用户
    • 删除用户
    • 查看用户
    • 更新用户信息

7.1 创建表结构

create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
use unicom;
create table admin(
    id int not null auto_increment primary key,
    username varchar(16) not null,
    password varchar(64) not null,
    mobile char(11) not null
) default charset=utf8;

7.2 Python操作MySQL

用Python代码连接MySQL并发送指令。

pip install pymysql

1.插入数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
 
# 2.发送指令
cursor.execute("insert into admin(username,password,mobile) values('wupeiqi','qwe123','15155555555')")
conn.commit()

# 3.关闭
cursor.close()
conn.close()
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令(千万不要用format字符串格式化去做SQL的拼接,安全隐患SQL注入)
sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql, ["韩超", "qwe123", "1999999999"])

sql = "insert into admin(username,password,mobile) values( %(n1)s, %(n2)s, %(n3)s)"
cursor.execute(sql, {"n1": "集宁", "n2": "qwe123", "n3": "1999999999"})

conn.commit()

# 3.关闭
cursor.close()
conn.close()
import pymysql

while True:
    user = input("用户名:")
    if user.upper() == 'Q':
        break
    pwd = input("密码:")
    mobile = input("手机号:")

    # 1.连接MySQL
    conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 2.发送指令(千万不要用fromat字符串格式化去做SQL的拼接,安全隐患SQL注入)
    sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
    cursor.execute(sql, [user, pwd, mobile])
    conn.commit()

    # 3.关闭
    cursor.close()
    conn.close()

2.查询数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("select * from admin where id > %s", [2, ])

# fetchall 获取符合条件的所有数据,得到的是 [ {字典},{字典}, ]    空列表
data_list = cursor.fetchall()
for row_dict in data_list:
    print(row_dict)

# 3.关闭连接
cursor.close()
conn.close()
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("select * from admin where id > %s", [2, ])

# fetchone 获取符合条件的第一条数据,字典    None
res = cursor.fetchone()
print(res)  # {'id': 3, 'username': 'xx', 'password': 'xxx', 'mobile': '1999999999'}

# 3.关闭连接
cursor.close()
conn.close()

3.删除数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("delete from admin where id=%s", [3, ])
conn.commit()

# 3.关闭
cursor.close()
conn.close()

4.修改数据
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("update admin set mobile=%s where id=%s", ["1888888888", 4, ])
conn.commit()

# 3.关闭
cursor.close()
conn.close()

强调:

  • 在进行 新增、删除、修改时,一定要记得commit,不然数据库么有数据。
cursor.execute("..")
conn.commit()
  • 在查询时,不需要commit,执行fetchall / fetchone
cursor.execute("...")

# 查询 符合条件的 第一条数据,字典,无数据时是空列表
v1 = cursor.fetchone()

# 查询 符合条件的 所有数据,列表套字典,无数据时是None
v1 = cursor.fetchall()
  • 对于SQL语句不要用Python的字符串格式化进行拼接(会被SQL注入),一定要用execute+参数
cursor.execute(".%s..... %s", ["xx","xx"])

8.案例:Flask+MySQL

8.1 新增 & 查询用户数据

在这里插入图片描述

通过python和html实现:
1) 借助falsk向浏览器展示收集信息的页面,
2) 将收集到的用户信息写入到数据库add_user.html(收集数据的页面),
3)将数据库的信息在页面上进行展示show_user.html(动态消费数据库信息)[html可以写循环]。
实现: 一个页面(add/user)实时新增数据,同时另一个页面(show/user)查询所有用户数据


import pymysql
from flask import flask, render_template, request
app = flask(__name__)

@app.route('/add/user', methods = ['GET','POST'])
def add_user():
    if request.method == 'GET':
        return render_template('add_user.html')
    user_name = request.form.get('user_name')
    password = request.form.get('pwd')
    mobile = request.form.get('mobile')

    while True:
        if len(user_name) > 0:
            break
        # 1.连接MySQL
        conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

        # 2.发送指令(千万不要用fromat字符串格式化去做SQL的拼接,安全隐患SQL注入)
        sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
        cursor.execute(sql, [user_name, password, mobile])
        conn.commit()

        # 3.关闭
        cursor.close()
        conn.close()

    return "添加成功"


@app.route("/show/user")
def show_user():
    # ########## 从数据库获取所有用户信息 ###########
    # 1.连接MySQL
    conn = pymysql.connect(host="127.0.0.1", port=3306, user='xxx', passwd="xxx", charset='utf8', db='unicom')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 2.发送指令
    sql = "select * from admin"
    cursor.execute(sql)
    data_list = cursor.fetchall()

    # 3.关闭
    cursor.close()
    conn.close()

    print(data_list)
    # 1.找到index.html的文件,读取所有的内容。
    # 2.找到内容中 `特殊的占位符` ,将数据替换。
    # 3.将替换完成的字符串返回给用户的浏览器。
    return render_template('show_user.html',data_list=data_list)


if __name__ == '__main__':
    app.run()
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>xx录入会员信息系统</title>
  </head>
  <body>
    <h2>请输入需要录入的会员信息</h2>
    <form method="POST", action="/add/user">
      <input type="text", name = 'user', placeholder="用户名">
      <input type="text", name ='pwd', placeholder="密码">
      <input type="text", name = 'mobile', placeholder="手机号">
      <input type="submit", value="提交">
    </form>

  </body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.4.1/css/bootstrap.css">
</head>
<body>
<div class="container">
    <h1>用户列表</h1>
    <table class="table table-bordered">
        <thead>
        <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>密码</th>
            <th>手机号</th>
        </tr>
        </thead>
        <tbody>
        {% for item in data_list %}
        <tr>
            <td>{{ item.id }}</td>
            <td>{{ item.username }}</td>
            <td>{{ item.password }}</td>
            <td>{{ item.mobile }}</td>
        </tr>
        {% endfor %}

        </tbody>

    </table>
</div>


<script src="/static/js/jquery-3.6.0.min.js"></script>
<script src="/static/plugins/bootstrap-3.4.1/js/bootstrap.js"></script>
</body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值