首页 > 数据库 >(学习日记)四、数据库MySQL

(学习日记)四、数据库MySQL

时间:2024-02-16 13:56:56浏览次数:21  
标签:-- 数据库 mysql cursor MySQL password 日记 conn

1.初识网站

  • 默认编写的网站是静态的
  • 动态需要用到web框架的功能
from flask import Flask,render_template

app = Flask(__name__)

@app.route("/index")
def index():
    users = {"Wu":"1", "Liu":"2", "Deng":"3" }#此处的数据应该由什么来存储呢?

    '''
    > 找到index.html文件,读取所有内容
    > 找到内容中的特殊占位符{{}},将数据替换
    > 将替换完成的字符串返回给用户的浏览器
    '''
    return render_template("index.html", title = "数据表单", datadict = users)

if __name__ == "__main__" :
    app.run(debug=True)

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

  • txt文件(效率不高)
  • excel文件(效率不高)
  • 存储数据的专业软件(DBMS)
MySQL/Oracle/SQserver/DB2/Access...

MySQL组成:解析指令|文件夹、文件

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

2.安装&启动MySQL

2.1安装版本

MySQL本质是一个数据库软件

  • 5.7.31版本
    • 补丁1:vcredist_x64.exe
    • 补丁2:dxwebsetup.exe
  • 创建配置文件
[mysqld]

port=3306
#bin所在目录
basedir=C:\\Program Files (x86)\\MySQL\\mysql-5.7.44-winx64
#数据文件所在目录
datadir=C:\\Program Files (x86)\\MySQL\\mysql-5.7.44-winx64\\data

2.2初始化

  • 打开终端(cmd)以管理员权限运行
  • 输入初始化命令
>>> "C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin\mysqld.exe"  --initialize-insecure
  • 执行命令后会在MySQL目录下新增一条data的目录

2.3启动MySQL

  • 临时启动:在终端启动mysqld,关闭终端,自动关闭MySQL
>>> "C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin\mysqld.exe"
  • 制作成Windows服务,服务来进行关闭和开启

    • 制作服务
    >>> "C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin\mysqld.exe"  install mysql5744
    
    • 启动和关闭服务 --指令方式
    >>> net start mysql5744
    >>> net stop mysql5744
    
    • 启动和关闭服务 --桌面任务栏

    在任务管理器 -> 服务 ->搜索mysql5744 ->右键启动/停止

3.连接测试

使用MySQL自带工具连接

  • 标准写法(连接某台电脑上的mysql)
>>> "C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin\mysql.exe" -h 127.0.0.1 -P 3306 -u root -p
  • 在本地执行
>>> "C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin\mysql.exe" -u root -p
  • 将bin目录添加到系统的环境变量(之后无需输入"C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin" 等前缀目录):

​ 设置 -> 系统高级设置 -> 配置环境变量 -> PATH -> 添加 -> 输入"C:\Program Files (x86)\MySQL\mysql-5.7.44-winx64\bin"

​ 之后直接打开终端输入

>>> mysql -u root -p

3.1设置密码

set password = password("xxxxxxx");

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

show databases;

3.3关闭连接

exit;

3.4再登录(需提供密码)

>>> mysql -u root -p

4.忘记密码

默认情况下,启动mysql需要用户输入账号和密码,若忘记密码:

修改mysql配置,重新启动mysql(无账号模式)
				V
		mysql -u root -p
				V
			重新设置密码
				V
			   退出
			    V
再重新修改mysql的配置文件,重新启动mysql(需要账号的模式)
				V
	    mysql -u root -p
	    		V
	    	  新密码   	
  • 停止mysql现在的服务
  • 修改mysql配置文件(my.ini),添加以下内容
skip-grant-tables=1
  • 重新启动mysql(无需密码)
  • 设置密码,先执行
use mysql;

​ 然后执行

update user set authentication_string = password('123'), password_last_changed = now() where user ='root';
  • 重新修改配置文件(需要账号的模式登录)(停止服务)
删除 skip-grant-tables=1
  • 重新启动mysql
  • 再次登录mysql,重新输入密码

小结

安装, 配置, 启动, 连接

之后的操作

启动-连接-退出-关闭

5.MySQL指令

MySQL 对应

数据库 文件夹

数据表 文件

5.1数据库管理(文件夹)

1.查看已有的数据库

show databases;

2.创建数据库(文件夹)

--默认GBK格式
create database 数据库名字;

--改成以utf-8为编码格式创建(推荐)
create database 数据库名字 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

3.删除数据库(文件夹)

drop database 数据库名字;

4.进入数据库(进入文件夹)

use 数据库名字;

5.查看数据库(文件夹)下所有的数据表(文件)

show tables;

5.2数据表管理(文件)

1.创建表(文件)

create table 表名称(
	列名称 类型,
    列名称 类型,
    列名称 类型
)default charset=utf8;
create table users(
	id int,
    name varchart(16),
    age int
)default charset=utf8;
id int not null, --表示该属性不能为空

id int primary key, --表示该属性为主键(不允许为空,不允许重复)

id int auto_increment primary key, --表示该属性为主键,且无需传值,内部维护自增

age int null, --表示该属性允许为空

age int default 3, --为该属性设置一个默认值,不填则为该值

2.创建表(标准格式)

create table users(
	id int auto_increment primary key,
    name varchar(16) not null,
    age int default 20
)default charset=utf8;

3.删除表

drop table 表名称;

4.查看表的属性描述

desc 表名称;

常用数据类型

  • tinyint(1byte)
xxx tinyint, --有符号

yyy tinyint unsigned, --无符号
  • int(4byte)
  • bigint(8byte)

练习:

#创建表
create table users(
	id int auto_increment primary key,
    name varchar(16) not null,
    age tinyint unsigned default 20
)default charset=utf8;

#插入数据
insert into users(name, age) values("Li Min", 20); --单项插入
insert into users(name, age) values
("Li Min", 18),
("Zhang He", 22),
("Liu Bei", 23);
  • float
  • double
  • decimal(精准)
decimal(n, m) --n表示数字总位数(最大为65),m是小数点后个数(最大为30)

salary decimal(4, 2),

insert into tb(salary) values(1.28), (3.77), (8.43432);
  • char
--定长字符串
mobile char(11), --表示固定用11个字符长度存储mobile
  • varchar
--变长字符串
mobile varchar(11), --真实数据有多长就按照多长的字符串存储,但是在11(括号内的数字)以外仍会报错
  • text
--可容纳大量字符,可用于短篇文章如新闻等,最多容纳65535个字符

create table news(
	id int auto_increment primary key,
    title varchar(15) not null,
    body text
)default charset=utf8;
  • mediumtext
  • longtext
--可容纳更多字符
  • datetime
--YYYY-MM-DD HH:MM:SS(2024-1-28 01:33:55)存储年月日时分秒
  • date
--YYYY-MM-DD 仅年月日

练习题:创建一张用户表

create table user_info(
	id int auto_increment primary key,
    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 user_info(name, password, email, age, salary, ctime) values
("Zhang He", "123123", "[email protected]", 23, 4500.23, "2024-1-28 01:33:55");

5.3数据行操作

1.新增数据

insert into 表名(属性名) values(值, 值);

insert into 表名(属性名) values(值, 值), (值, 值), (值, 值);

insert into user_info(name, password, email, age, salary, ctime) values
("Sun Liang", "126126", "[email protected]", 22, 4000.23, "2024-1-29 12:14:22"),
("Liu Ye", "128128", "[email protected]", 29, 6000.23, "2024-1-29 12:14:22"),
("Sun Liang", "129129", "[email protected]", 20, 5000.23, "2024-1-29 12:14:22"),
("Cao Rui", "130130", "[email protected]", 45, 10000.23, "2024-1-29 12:14:22");

2.删除数据

delete from 表名;
delete from 表名 where 条件;
delete from 表名 where 条件1 and 条件2;

delete from user_info where id=3;
delete from user_info where id<6;
delete from user_info where id!=3;
delete from user_info where id in (1,5);

3.修改数据

update 表名 set 列=值;
update 表名 set 列=值, 列=值, 列=值;
update 表名 set 列=值 where 条件;

update user_info set password="111111"; --将表中所有的password都改成111111
update user_info set password="111111" where id>5; --将符合条件的行的password属性值修改为111111
update user_info set age=age+10; --所有的age属性值在原有基础上+10

4.查询数据

select * from 表 --查询表中的所有数据
select 属性 from 表 --查询某一列
select 属性, 属性 from 表 --查询多个列
select 属性, 属性 from 表 where 条件 --查询多个符合条件的列

select name, salary from user_info where id>2;

小结

开发系统一般情况下:

  • 创建数据库
  • 创建数据表

通过工具+命令进行设置

表中的数据,通过程序实现

6.案例:员工管理

  • 使用MySQL内置工具(命令)

    • 创建数据库:unicom

    • 数据一张表:admin

      表名:admin
      列:
      	id, 整型, 自增, 主键,
      	username 字符串 不为空,
      	password 字符串 不为空,
      	mobile 字符串 不为空
      
  • Python代码实现:

    • 添加用户
    • 删除用户
    • 查看用户
    • 更新用户信息

6.1 创建数据库-数据表

create database unicom DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
 
use unicom;

create table admin(
 	id int auto_increment primary key,
     username varchar(32) not null,
     password varchar(32) not null,
     mobile char(11) not null
 )default charset=utf8;
mysql> desc admin;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| username | varchar(32) | NO   |     | NULL    |                |
| password | varchar(32) | NO   |     | NULL    |                |
| mobile   | char(11)    | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

7.2Python操作MySQL

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

安装pymysql

E:\TestEnv>Scripts\activate.bat

(TestEnv) E:\TestEnv>pip install pymysql

1.创建数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='123', charset='utf8', db='unicom')#conn是建立与数据库的连接
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#基于cursor来发送指令


#2.发送指令
sql = "insert into admin(username, password, mobile) values('Zhang He', 'qwer123', '15555555555')"
cursor.execute(sql)
conn.commit()

#3.关闭连接
cursor.close()
conn.close()
#2.发送指令(键入数据,不要用字符串格式去做SQL拼接防止SQL注入)
sql = "insert into admin(username, password, mobile) values(%s, %s, %s)"
cursor.execute(sql, ["Zhang He", "qwe456", "19999999999"])
conn.commit()
#2.发送指令(键入数据,不要用字符串格式去做SQL拼接防止SQL注入)
sql = "insert into admin(username, password, mobile) values(%(n1)s, %(n2)s, %(n3)s)"
cursor.execute(sql, {"n1":"Zhang He", "n2":"qwe456", "n3":"19999999999"})
conn.commit()

动态创建数据

import pymysql

while True:
    username = input("Please input your username:")
    if username.upper() =='Q':
        break
    psw = input("Please input your password:")
    mobile = input("Please input your mobile:")

    # 1.连接MySQL
    conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='123', charset='utf8', 		db='unicom')#conn是建立与数据库的连接
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#基于cursor来发送指令


    #2.发送指令(***键入数据,不要用字符串格式去做SQL拼接防止SQL注入***)
    sql = "insert into admin(username, password, mobile) values(%(n1)s, %(n2)s, %(n3)s)"
    cursor.execute(sql, {"n1":username, "n2":psw, "n3":mobile})
    conn.commit()

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

2.查询数据

查询符合要求的全部数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='123', charset='utf8', db='unicom')#conn是建立与数据库的连接
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#基于cursor来发送指令


#2.执行查询指令
sql = "select * from admin"
cursor.execute(sql)

datalist = cursor.fetchall()#fetchall()获取符合条件的全部数据
#print(datalist)
for row in datalist:
    print(row)#以列表套字典的形式返还

conn.commit()

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

查询符合条件的第一条数据

res = cursor.fetchone()#fetchone()仅获取符合要求的第一条数据
print(res)

3.删除数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='123', charset='utf8', db='unicom')#conn是建立与数据库的连接
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#基于cursor来发送指令


#2.执行查询指令
sql = "delete from admin where id=%s"
cursor.execute(sql, [1, ])
conn.commit()

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

4.修改数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='123', charset='utf8', db='unicom')#conn是建立与数据库的连接
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#基于cursor来发送指令


#2.执行查询指令
sql = "update admin set mobile=%s where id=%s"
cursor.execute(sql, ["15566667777",3 ])
conn.commit()

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

强调:

  • 在进行增删改查时,一定要记得commit,不然数据库得不到数据

    cursor.execute("...")
    conn.commit()
    
  • 在查询时,不需要commit,执行fetchall/fetchone

    cursor.execute("...")
    
    #第一条数据,字典类型,无数据时是None
    v1 = cursor.fetchone()
    
    #所有数据,列表类型,无数据时是空列表
    v2 = cursor.fetchall()
    
  • 对于SQL语句不要用Python的字符串格式化进行拼接,一定要用execute+参数

    cursor.execute("...%s...%s", ["xx", "yy"])
    

7.3案例:MySQL + Flask

1.添加用户

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

    if username == "" or password == "" or mobile=="":
        return "ERROR! Please Input Correct String!"
    
    #1.连接MySQL
    conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', password='123', charset='utf8', db='unicom')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    #2.发送指令
    sql = "insert into admin(username, password, mobile) values(%(n1)s, %(n2)s, %(n3)s)"
    cursor.execute(sql, {"n1":username, "n2":password, "n3":mobile})
    conn.commit()
    
    #3.关闭连接
    cursor.close()
    conn.close()  

    users = datalist
    return render_template("add_user.html", datadict = users)

2.查询所有用户

@app.route("/add/user", methods=["GET", "POST"])
def add_user():

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

    #2.发送指令
    sql = "select * from admin"
    cursor.execute(sql)
    datalist = cursor.fetchall()
    conn.commit()
    
    #3.关闭连接
    cursor.close()
    conn.close()    

    
    users = datalist
    return render_template("add_user.html", datadict = users)

标签:--,数据库,mysql,cursor,MySQL,password,日记,conn
From: https://www.cnblogs.com/gin49sz/p/18017064

相关文章

  • MSSQL Server 备份数据库脚本
    备份数据库脚本,实现如下脚本1.定时备份2. 平日以N开头,周一以W开头,每月1号以M开头,每年1月1日以Y开头, (保留最近7天,4周,12月和10年的备份)3.每周一还原备份到test库,并将密码改为123 declare@bakfilevarchar(100),@dbvarchar(100),@prevarchar(......
  • MySQL 主从数据库同步是如何实现的?
    回顾我们之前讲MySQL相关的几节课程,你会发现 主从同步有多重要:解决数据可靠性的问题需要用到主从同步;解决MySQL服务高可用要用到主从同步;应对高并发的时候,还是要用到主从同步。我们在运维MySQL集群时,遇到的很多常见的问题,比如说:为什么从节点故障会影响到主节点?为......
  • Java学习日记 Day16 正月初五,学习回归正轨!
    年前把SSM和Linux学完了,过年期间简单的做了个ssm的项目,再理解理解SSM。今天继续学了radis,也是比较重要的一个技术。radis:简单来说就是把数据存到缓存里的技术,常常和关系数据库结合使用,我们可以把数据库拿出来的数据存到缓存里,这样减少了io的次数,大大提高了效率。radis的学习大......
  • 【性能测试】MYSQL锁和mysql事务问题排查04
    一、MYSQL锁目的:解决客户端并发访问冲突问题查看死锁showOPENTABLESwhereIn_use>0案例登录接口 #锁定表LOCKTABLESlitemall.litemall_userREAD;#睡眠160秒SELECTSLEEP(160);#解锁表UNLOCKTABLES;当用户表被锁定时,接口无法登录访问,解锁后可以正......
  • pymysql
    PyMySQL(1)简介PyMySQL是一个用于Python的纯PythonMySQL客户端库,它实现了MySQL协议,可以与MySQL服务器进行通信。它允许Python开发人员在其应用程序中轻松地与MySQL数据库进行交互,执行查询、插入、更新和删除数据等操作。PyMySQL被广泛用于PythonWeb开发、数据分......
  • 【性能测试】MYSQL缓存命中率03
    一、查询缓存(querycache) 缓存命中率:所有的查询语句,命中缓存的请求数,占所有请求数的比例查看是否开启缓存命中率#缓存的开关showvariableslike'%query_cache_type%';#缓存的大小showvariableslike'%query_cache_size%';开启缓存设置MySQL的配置文件my......
  • MySQL - 创建高性能索引
    索引基础要理解MySQL中索引是如何工作的,最简单的办法就是去看看一本书的"索引"部分:如果想要在一本书中找到某个特定主题,一般会先看书的"索引",找到对应的页码在MySQL中,存储引擎用类似的方法使用索引,其先在索引中找到对应值,然后根据匹配的索引记录找到对应的数据行。假如要运行......
  • 2024寒假年后集训日记
    2.14闲话做题纪要SP913QTREE2-QueryonatreeII\(LCA\)板子。点击查看代码structnode{ llnxt,to,w;}e[20002];llhead[20002],dep[20002],dis[20002],fa[20002][25],N,cnt=0;voidadd(llu,llv,llw){ cnt++; e[cnt].nxt=head[u]; e[cnt].to=v; e[cnt......
  • 第二十二天:mysql并发控制及事务日志
    一、锁机制锁类型:读锁:共享锁,也称为S锁,只读不可写(包括当前事务),多个读互不阻塞写锁:独占锁,排它锁,也称为X锁,写锁会阻塞其它事务(不包括当前事务)的读和写S锁和S锁是兼容的,X锁和其它锁都不兼容,举个例子,事务T1获取了一个行r1的S锁,另外事务T2可以立即获......
  • MySQL笔记
    MySQL查看表结构简单命令创建数据库:CREATEDATABASETest1Spider使用数据库:usetest1spider删除表:DROPTABLE语句用于删除数据库中的现有表。--删除表,如果存在的话DROPTABLEIFEXISTSmytable;--直接删除表,不检查是否存在DROPTABLEmytable;创建表CREATETABLE......