概要
1.mysql的安装&配置
2.mysql的启动&关闭
3.mysql操作指令
4.python第三方模块,发送指令并获取MYSQL返回的结果
一.mysql的安装&配置
1.下载:https://downloads.mysql.com/archives/community/
2.安装:如果初始化过程中出现dll文件缺失,就安装官方补丁.
3.解压:官方免安装,解压即可
4.配置文件
(1).在安装目录新建my.ini
(2).在文件内输入
[mysqld]
port=3306
basedir=E:\\mysql\\mysql-5.7.31-winx64
datadir=E:\\mysql\\mysql-5.7.31-winx64\\data
5.初始化:
(1).打开终端以管理员的权限运行
(2).输入: “E:\mysql\mysql-5.7.31-winx64\bin\mysqld.exe” --initialize-insecure
二.mysql的启动&关闭
启动mysql
1.临时启动:终端输入路径,不可关闭终端
2.制作成windows服务,服务来启动和关闭
(1).制作服务:“E:\mysql\mysql-5.7.31-winx64\bin\mysqld.exe” --install mysql57
见到这段话,就说明服务器创建成功: Service successfully installed.
(2).启动和关闭服务:
终端:
启动:net start mysql57
关闭:net stop mysql57
桌面任务管理器:
在服务里面找到mysql57,手动或自动启动关闭.
连接测试
1.连接mysql: 输入: mysql -u root -p (前提是将mysql.exe所在文件夹加入环境变量,否则需要输入完成路径)
2.进入后:
1.设置密码: 输入:set password = password(‘********’);
2.查看mysql已有的文件夹(数据库): 输入:show databases;
3.退出(关闭连接):输入:exit;
修改密码
1.关闭mysql服务
2.修改my.ini:在最后加 skip-grant-tables=1(改为无账号模式)
3.启动服务
4.无账号登录
5.修改密码指令:
1.use mysql;
2.update user set authentication_string = password(‘新密码’), password_last_changed = now() where user = ‘root’;
3.退出mysql
6.修改配置文件:删除 skip-grant-tables=1
如果不允许删除,关闭服务再操作
7.在登陆即可输入新密码登录
三.mysql操作指令
3.1数据库管理
1.查看已有的数据库(文件夹):
show databases;
2.创建数据库(文件夹):
create database 数据库名字 (后面这段为了防止代码出错而写) DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
# shiyan01为创建的库
create database shiyan01 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
3.删除数据库(文件夹):
drop database 数据库名字;
4.进入数据库(文件夹):
use 数据库名字;
5.查看数据库(文件夹)下所有的数据表(文件):
show tables;
3.2 数据表的管理
1.创建表(文件):
# 1
create table lst_name(
列名称 类型,
列名称 类型 not null(不允许为空),
列名称 类型 null(允许为空,默认是可以为空的)
)default charset=utf8;
# 2
create table tb1(
id int,
name varchar(16), # 字符串长度不超过16
age int default 3 # 插入数据时,age列默认为3
) default charset=utf8;
# 3
create table tb1(
id int primary key, # 把id列设为主键 不允许为空,不允许重复
name varchar(16), # 字符串长度不超过16
age int default 3 # 插入数据时,age列默认为3
) default charset=utf8;
# 主键一般用于表示当前行数据的编号(类似于人的身份证)
# 4
create table tb1(
id int auto_increment primary key, #内部维护 自增
name varchar(16), # 字符串长度不超过16
age int default 3 # 插入数据时,age列默认为3
) default charset=utf8;
# 5.一般情况,创建表时这样写:
create table tb1(
id int not null auto_increment primary key,
name varchar(16),
age int default 3
) default charset=utf8;
2.查看表列数据类型:
desc 表名称;
desc tb1;
3.删除表:
drop table 表名称;
drop table tb2;
四.常见数据类型
1 整数
1.tinyint
1)有符号:取值范围 -128~127 (有正负数) 【默认】
create table tb1(
id int not null auto_increment primary key,
age tinyint
) default charset=utf8;
2)无符号:取值范围 0~255 (只有正数) 【unsigned】添加后就有符号
create table tb1(
id int not null auto_increment primary key,
age tinyint unsigned
) default charset=utf8;
2.int
1)有符号:取值范围 -2141473648~2141473647 (有正负数) 【默认】
2)无符号:取值范围 0~42949675 (只有正数) 【unsigned】添加后就有符号
3.bigint
1)有符号:取值范围 (有正负数) 【默认】
2)无符号:取值范围 (只有正数) 【unsigned】添加后就有符号
练习:
1.创建tb2
create table tb2(
id bigint not null auto_increment primary key,
salary int,
age tinyint
)default charset=utf8;
2.插入数据
1.id时自增,所以不用添加
2.插一行:insert into tb2(salary, age) values(10000, 18);
3.插四行:insert into tb2(salary, age) values(10000, 18),(10000, 18),(10000, 18),(10000, 18);
3.查看表中数据:
1.查看表中所有数据:select * from tb2;
mysql> select *from tb2;
2.小数
1.float
2.double
3.decimal
decimal(m, d):准确的小数值,m是数字总个数,负号不算,d是小数点后数字个数,m最大值是65,d最大值是30
例如
1.创建decimal表:
create table tb3(
id int not null auto_increment primary key,
salary decimal(8, 2)
)default charset=utf8;
2.插入数据
insert into tb3(salary) values(6000.33),(52.369),(123.9);
3.查看表内容
select * from tb3;
3.字符串
1.char:速度快
定长字符串。char(11):固定用11个字符串存储,即使不足11个,也会按照11个存储 最多可容纳255个字节
create table tb4(
id int not null auto_increment primary key,
mobile char(11)
)default charset=utf8;
insert into tb4(mobile) values("15652");
insert into tb4(mobile) values('15569859545');
mysql> select * from tb4;
+----+-------------+
| id | mobile |
+----+-------------+
| 1 | 15569859545 |
| 2 | 15652 |
+----+-------------+
2 rows in set (0.00 sec)
2.varchar:节省内存
变长字符串.char(11):真实数据有多长就按多长存储,但不能超过11,最多可容纳65535个字节
create table tb5(
id int not null auto_increment primary key,
mobile varchar(11)
)default charset=utf8;
insert into tb5(mobile) values("1223452");
insert into tb5(mobile) values('16598745693');
3.text
text数据类型用于保持变长的大字符串,最大可以存储65535个字符
一般长文本会用text类型,例如:文章,新闻等
create table tb6(
id int not null auto_increment primary key,
title varchar(12),
content text
)default charset=utf8;
4.mediumtext
5.longtext
4.时间
1.datetime 年月日 时分秒 xxxx-xx-xx xx:xx:xx
2.date 年月日 xxxx-xx-xx
#练习:注册信息表
create table tb7(
id int not null auto_increment primary key,
name varchar(64) not null,
password char(64) not null,
email varchar(64),
age tinyint,
salary decimal(10, 2),
c_datetime datetime
)default charset=utf8;
insert into tb7(name, password, email, age, salary, c_datetime) values("joker", "15569878965", "598@sdasd.com", 40, 10000.99, "2023-06-04 13:58:58");
mysql> select * from tb7;
五.数据行操作
5-1 终端操作
新增
1.新增一行:insert into 表名(列,列) values(值,值);
2.新增多行:insert into 表名(列,列) values(值,值),(值,值),(值,值),(值,值);
insert into tb7(name,password,email,age,salary,c_datetime) values('joker','123','123@163.com',18,10000,'2023-06-29 12:12:12');
删除
# 1.删除全部内容:delete from 表名;
# 2.删除符合条件的:delete from 表名 where 条件;
# 删除id=3的行
delete from tb7 where id=3;
# 删除id=2或name='joker'的行
delete from tb7 where id=2 or name="jocker";
# 多条件删除
delete from tb7 where id != 1 / id <=4/ id=4 and name="sdads"
修改
# 1.修改一列:update 表名 set 列=值;
update tb7 set password='123456';
# 2.修改多列:update 表名 set 列=值,列=值;
update tb7 set password='123456',age=30;
# 3.修改符合条件的: update 表名 set 列=值 where 条件;
update tb7 set email="呵呵" where id >=14;
update tb7 set age=age-10 where name="ssd";
update tb7 set name='asd', email="2sads9@qq.com", age=40, salary=100000 where id =12;
查询
# 1.查询全部:select * from 表名;
select * from tb7;
# 2.查询一列或多列:select 列名,列名 from 表名;
select id ,name from tb7;
# 3.按条件查找:select 列名,列名 from 表名 where 条件.
select id, name, password, age from tb7 where id=14;
5-2 python 操作
终端
# 1.创建数据库:
create database shiyan02 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
# 2.进入数据库:
use unicom;
# 3.创建表:
create table admin(
id int not null auto_increment primary key,
username varchar(64) not null,
password varchar(64) not null,
mobile char(11)
)default charset=utf8;
# 4.安装第三方模块:
pip install pymysql
python
导入pymysql
# 1.导入pymysql
import pymysql
连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='********', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
发送指令
新增
# 方法1
cursor.execute("insert into admin(username, password, mobile) values ('asd', '1233', 11232136341)")
conn.commit()
# 方法2
sql = "insert into admin(username, password, mobile) values (%s, %s, %s)"
cursor.execute(sql, ['wasdsn', 'asdsad903', asdsadsa])
conn.commit()
# 方法3
sql = "insert into admin(username, password, mobile) values (%(n1)s, %(n2)s, %(n3)s)"
cursor.execute(sql, {'n1': '苏有朋', 'n2': 'syp123456', 'n3': 12345678911})
conn.commit()
关闭连接
cursor.close()
conn.close()
用户操作python将信息输入数据库
username = input('用户名:')
password = input('密码:')
mobile = input('手机号:')
python增删改查
代码
# python数据库表信息增删改查:
import pymysql
# 1.连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='********', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 2.操作
# 1.增加
sql = "insert into admin(username, password, mobile) values (%s, %s, %s)"
cursor.execute(sql, ['范冰冰', 'fbb123456', 11111111111])
conn.commit()
# 2.删除
cursor.execute("delete from admin where id = %s", [3, ])
conn.commit()
# 3.修改
cursor.execute("update admin set mobile = %s where id = %s", ['18888888888', 5])
conn.commit()
# 4.查询
cursor.execute("select * from admin where id > %s", [2, ])
res = cursor.fetchone() # 逐条数据 是字典 没有数据返回[]
data_lst = cursor.fetchall() # 获取符合条件的全部数据 ,数据是个列表,列表元素是字典,没数据就是None
# 3.关闭连接
cursor.close()
conn.close()
实例
import pymysql
# 连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='********', charset='utf8', db='shiyan02')
# 通过cursor对数据增删改查
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 循环增加数据
while True:
user_name = input('username:').strip()
if user_name == 'q':
break
pass_word = input('password:').strip()
mo_bile = input('mobile:').strip()
sql = "insert into admin(username, password, mobile) values (%s, %s, %s)"
cursor.execute(sql, [user_name, pass_word, mo_bile])
conn.commit()
# 删除id=5的数据行
# cursor.execute("delete from admin where id = %s", [5, ])
# conn.commit()
# 修改符合条件的
cursor.execute("update admin set username=%s,password=%s,mobile=%s where id = %s", ['BOSD', 'abcd', 'abcdef', 3])
conn.conmit() # 如果没有这句话 只会在python修改 数据库不会修改
# 查询符合条件的数据
cursor.execute("select * from admin where id > 2")
# 获取第一条
res = cursor.fetchone()
print(res)
# 获取剩下的所有数据
data_lst = cursor.fetchall()
print(data_lst)
# 关闭连接
cursor.close()
conn.close()
六.mysql与flask
6-1 python代码
# 导入模块
from flask import Flask, render_template, request
import pymysql
# 创建app对象
app = Flask(__name__)
# 输入ip+/add/user进入add_user.html
@app.route("/add/user", methods=['GET', 'POST'])
def add_user():
# 如果响应方式是get,进入页面
if request.method == 'GET':
return render_template("add_user.html")
# 如果响应方式是post
# print(request.form)
# 获取提交的表单信息
username = request.form.get('user')
password = request.form.get('paswd')
mobile = request.form.get('mobile')
# 连接数据库unicom
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='*********', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 向数据库中的admin表格添加数据
sql = "insert into admin(username, password, mobile) values (%s, %s, %s)"
cursor.execute(sql, [username, password, mobile])
conn.commit()
# 关闭数据库连接
cursor.close()
conn.close()
# 网页提交成功后返回的信息
return "添加成功"
# 输入ip+/show/user指向template目录下的show_user.html
@app.route('/show/user')
def show_user():
# 连接数据库
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='********', charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 查询admin表格
sql = "select * from admin"
cursor.execute(sql)
# 获取表格中的所有数据,是列表套字典
dict_list = cursor.fetchall()
# 关闭服务器连接
cursor.close()
conn.close()
print(dict_list)
# 输入网址 只想html页面,并向页面提交data_list信息
return render_template('show_user.html', data_list=dict_list)
if __name__ == '__main__':
# 运行app对象
app.run()
6-2 add_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
# form表单标签
# 提交方式post,对应的网址为/add/user
# python可以通过request.form获取表单提交的信息
<form method="post" action="/add/user">
<input type="text" name="user" placeholder="用户名">
<input type="text" name="paswd" placeholder="密码">
<input type="text" name="mobile" placeholder="手机号码">
<input type="submit" value="提交">
</form>
</body>
</html>
6-3 show_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
h1{
margin: 50px auto 50px;
align: center;
}
table{
border: rebeccapurple 1px solid;
margin: 50px auto 50px;
}
td{
border: rebeccapurple 1px solid;
}
th{
border: rebeccapurple 1px solid;
}
</style>
</head>
<body>
<h1 align="center">用户列表</h1>
<table>
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
<th>mobile</th>
</tr>
# python从数据库获取的列表信息传递到网页
# 注意这个循环书写的方式,以及从字典获取信息的方式
{% for dic in data_list %}
<tr>
<td>{{dic.id}}</td>
<td>{{dic.username}}</td>
<td>{{dic.password}}</td>
<td>{{dic.mobile}}</td>
</tr>
{% endfor %}
</table>
</body>
</html>