MySQL详细教程

文章目录

  • 前言
  • 一、数据库管理
    • 1.查看已有的数据库
    • 2.创建数据库
    • 3.删除数据库
    • 4.进入数据库
  • 二、 数据表管理
    • 1.查看当前数据库下的所有数据表
    • 2.创建数据表
    • 3.删除表
    • 4.查看表结构
  • 三、常用数据类型
    • 1.整型
      • tinyint
      • int
      • bigint
    • 2.浮点型
      • float
      • double
      • decimal
    • 3.字符型
      • char(m)
      • varchar(m)
      • text
      • mediumtext
      • longtext
    • 4.时间
      • datetime
      • date
    • 5.其他
  • 四、数据行操作
    • 1. 新增数据
    • 2.删除数据
    • 3.修改数据
    • 4.查询数据
  • 五、案例:员工管理
    • 1.任务
    • 2.创建表结构
    • 3.Python操作MySQL
      • 创建数据
      • 查询数据
      • 删除数据
      • 修改数据
      • 强调
  • 六、案例:用户管理(Flask + Mysql)
    • 1.main.py
    • 2.HTML

前言

MySQL是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,属于 Oracle 旗下产品。MySQL是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL是最好的RDBMS (Relational Database Management System,关系数据库管理系统)应用软件之一。
MySQL是一种关系型数据库管理系统,关系数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库内,这样就增加了速度并提高了灵活性。

一、数据库管理

数据库相当于文件夹

1.查看已有的数据库

show databases;

2.创建数据库

create database 数据库名字 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
  • 例子:
create database d1 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

3.删除数据库

drop database 数据库名字;

4.进入数据库

use 数据库名字;

二、 数据表管理

数据表相当于文件

1.查看当前数据库下的所有数据表

show tables;

2.创建数据表

create table 表名称(
	列名称 类型,
    列名称 类型,
    列名称 类型
)default charset=utf8;
  • 例子:
 create table tb1(id int, name varchar(16),age int) default charset=utf8;
create table tb1(
    id int, 
    name varchar(16),
    age int
) default charset=utf8;
create table tb1(
    id int, 
    name varchar(16) not null,   -- 不允许为空
    age int null,                -- 允许为空(默认)
) default charset=utf8;
create table tb1(
    id int, 
    name varchar(16),
    age int default 3        -- 插入数据时,age列的值默认3
) default charset=utf8;
create table tb1(
    id int primary key,     -- 主键(不允许为空,不允许重复)
                            --主键一般用于表示当前行的数据的编号(类似于人的身份证)
    name varchar(16),
    age int
) default charset=utf8;
create table tb1(
    id int auto_increment primary key, -- 内部维护,自增
    name varchar(16),
    age int
) default charset=utf8;
  • 一般情况下,我们再创建表时都会这样来写:【标准】
create table tb1(
    id int not null auto_increment primary key,
    name varchar(16),
    age int
) default charset=utf8;

3.删除表

drop table 表名称;

4.查看表结构

mysql> desc tb1;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| name  | varchar(16) | YES  |     | NULL    |                |
| age   | int(11)     | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

三、常用数据类型

1.整型

tinyint

  • 有符号,取值范围:-128 ~ 127 (有正有负)【默认】
  • 无符号,取值范围:0 ~ 255(只有正)
create table tb2(
    id int not null auto_increment primary key,
    age tinyint   -- 有符号:取值范围:-128 ~ 127
) default charset=utf8;
create table tb3(
    id int not null auto_increment primary key,
    age tinyint unsigned -- 无符号:取值范围:0 ~ 255
) default charset=utf8;

int

  • int 表示有符号,取值范围:-2147483648 ~ 2147483647
  • int unsigned 表示无符号,取值范围:0 ~ 4294967295

bigint

  • 有符号,取值范围:-9223372036854775808 ~ 9223372036854775807
  • 无符号,取值范围:0 ~ 18446744073709551615

2.浮点型

float

  • 占4个字节,精度是6位

double

  • double 占8个字节,精度是16位

decimal

  • 准确的小数值,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);
 
 select * from tb3;

3.字符型

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 (216 − 1)个字符。
  • 一般情况下,长文本会用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 (224 − 1) characters.

longtext

  • A TEXT column with a maximum length of 4,294,967,295 or 4GB (232 − 1)

4.时间

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)

5.其他

  • MySQL还有很多其他的数据类型,例如:set、enum、TinyBlob、Blob、MediumBlob、LongBlob 等,详细见官方文档:https://dev.mysql.com/doc/refman/5.7/en/data-types.html

四、数据行操作

数据行相当于文件中的某一行内容

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="哈哈哈";
update tb7 set email="哈哈哈" where id > 5;

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

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";

五、案例:员工管理

1.任务

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

    • 创建数据库:unicom

    • 数据一张表:admin

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

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

请添加图片描述

2.创建表结构

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;

3.Python操作MySQL

  • 用Python代码连接MySQL并发送指令。
pip install pymysql

创建数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", 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()
  • 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入
  • 要使用列表或者对象的方式
import pymysql

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

# 2.发送指令(千万不要用字符串格式化去做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='root', passwd="root123", charset='utf8', db='unicom')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 2.发送指令(千万不要用字符串格式化去做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()

查询数据

  • fetchall得所有满足条件的
import pymysql

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

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

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

# 3.关闭连接
cursor.close()
conn.close()
  • fetchone得第一个满足条件的
import pymysql

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

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

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

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

删除数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", 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()

修改数据

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", 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"])

六、案例:用户管理(Flask + Mysql)

1.main.py

from flask import Flask, render_template, request
import pymysql

app = Flask(__name__)


# 添加用户
@app.route("/add/user", methods=['GET', 'POST'])
def addUser():
    if request.method == 'GET':
        return render_template("addUser.html")
    else:
        username = request.form.get('user')
        password = request.form.get('pwd')
        mobile = request.form.get('mobile')

        # 1.连接Mysql
        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
                            passwd='Syz123!@#', charset='utf8', db='unicom')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

        # 2.发送指令
        sql = "insert into admin(username, password, mobile) values(%s, %s, %s);"
        cursor.execute(sql, [username, password, mobile])
        conn.commit()

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

        return "添加成功"



# 展示用户
@app.route("/show/user", methods=['GET', 'POST'])
def showUser():
    username = request.form.get('user')
    password = request.form.get('pwd')
    mobile = request.form.get('mobile')

    # 1.连接Mysql
    conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
                        passwd='Syz123!@#', 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()

    return render_template("showUser.html", data_list=data_list)
    


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5200, debug=True)

2.HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</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>
    
</body>

</html>
  • 添加界面:
    请添加图片描述
    请添加图片描述
  • 展示界面:
    请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/490607.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

错误 LNK1104 无法打开文件“mfc140.lib”

如图&#xff0c;编译一个别人已有的项目&#xff0c;我的编译报错为&#xff1a; 但是我所有文件夹全局搜索了一下&#xff0c;这个文件是存在的。但是当前项目访问不到。 更改方法&#xff1a;项目->属性->配置属性->VC目录->库目录 全局搜索找到mfc140.lib的…

【工具篇】总结比较几种绘画软件的优缺点

目录 一、Visio二、Processon三、draw.io四、亿图图示五、wps 写在文章开头&#xff0c;感谢你的支持与关注&#xff01;小卓的主页 一、Visio Visio 是微软公司开发的一款流程图和图表绘制软件。我们可以用它来创建各种类型的图表&#xff0c;如流程图、组织结构图、网络图、平…

计算机基础--发展史

1进化史 计算工具&#xff0c;机械计算机&#xff0c;电子计算机&#xff08;目前&#xff09; 1.1计算工具 1算筹&#xff0c;算盘&#xff08;这些都是计算工具&#xff0c;算数还是得靠大脑算 &#xff09; 2机械计算机 2.1帕斯卡计算器 2.2莱布尼茨乘法器 2.3Curta计数…

聚类分析|基于层次的聚类方法及其Python实现

聚类分析|基于层次的聚类方法及其Python实现 0. 基于层次的聚类方法1. 簇间距离度量方法1.1 最小距离1.2 最大距离1.3 平均距离1.4 中心法1.5 离差平方和 2. 基于层次的聚类算法2.1 凝聚&#xff08;Agglomerative&#xff09;2.3 分裂&#xff08;Divisive&#xff09; 3. 基于…

【蓝桥杯】tarjan算法

一.概述 Tarjan 算法是基于DFS的算法&#xff0c;用于求解图的连通性问题。 Tarjan 算法可以在线性时间内求出&#xff1a; 无向图&#xff1a; 割点与桥双连通分量 有向图&#xff1a; 强连通分量必经点与必经边 1.割点&#xff1a; 若从图中删除节点 x 以及所有与 x 关联的…

【Java项目】jspm九宫格日志网站

目录 背景 技术简介 系统简介 界面预览 背景 互联网的迅猛发展彻底转变了全球各类组织的管理策略。自20世纪90年代起&#xff0c;中国的政府机关和各类企业便开始探索利用互联网技术来处理管理信息。然而&#xff0c;由于当时网络覆盖不广、用户接受度不高、互联网法律法规…

一文说清:AI大模型在制造业中的应用类型

在过去的几年里&#xff0c;全球制造业的竞争格局正在发生重构&#xff0c;数字化和智能化成为推动变革的关键力量。AI 大模型作为一种通用人工智能技术&#xff0c;其革命性特征体现在能够生成代码、构建人机交互新模式&#xff0c;并与产品研发、工艺设计、生产作业、产品运营…

羊大师解析,孩子喝羊奶的好处

羊大师解析&#xff0c;孩子喝羊奶的好处 孩子喝羊奶有诸多好处。羊奶富含多种营养物质&#xff0c;包括蛋白质、脂肪、维生素和矿物质等&#xff0c;对孩子的生长发育和身体健康都有积极的促进作用。羊奶中的蛋白质含量丰富&#xff0c;且易于消化吸收。这些优质蛋白质可以为…

《海王2》观后感

前言 我原本计划电影上映之后&#xff0c;去电影院观看的&#xff0c;但时间过得飞快&#xff0c;一眨眼这都快4月份了&#xff0c;查了一下&#xff0c;电影院早就没有排片了&#xff0c;所以只能在B站看了&#xff0c;这里不得不吐槽一下&#xff0c;原来花了4块钱购买观看还…

Hudi部署

目录 前言 Hudi的介绍 一、Hudi是什么&#xff1f; 二、Hudi的特点功能和优势 三、Hudi的使用场景 Hudi的搭建部署 一、准备 二、搭建 1&#xff09;搭建JAVA环境和Hadoop环境 2&#xff09;部署zookeeper 3&#xff09;部署Spark on yarn 4&#xff09;部署maven环…

vue-quill-editor和vue-ueditor-wrap富文本编辑器应用

目录 一、vue-quill-editor 1.1、界面展示 1.2、代码介绍 1.2.1、安装 1.2.2、配置 1.2.3、代码应用 1.2.4、提取内容 二、vue-ueditor-wrap 2.1、界面展示 2.2、代码介绍 2.2.1、安装 2.2.2、配置 2.2.3、代码应用 一、vue-quill-editor 1.1、界面展示 文本输出…

[BT]BUUCTF刷题第8天(3.26)

第8天 Web [CISCN2019 华北赛区 Day2 Web1]Hack World 题目明确提示flag在flag表里的flag列&#xff0c;这里先尝试1 返回&#xff1a;你好&#xff0c;glzjin想要一个女朋友。 再尝试1&#xff0c;返回bool(false) 到这里就感觉是布尔盲注的题目类型了&#xff08;虽然我没…

RocketMQ学习笔记:消息存储模型,持久化文件,过期文件删除

这是本人学习的总结&#xff0c;主要学习资料如下 马士兵教育rocketMq官方文档 目录 1、消息存储结构1.1、CommitLog详解1.1.1、CommitLog存储的优点 1.2、ConsumeQueue详解1.3、Index详解 2、持久化文件3、过期文件删除机制3.1、判断过期文件3.2、删除的时机 1、消息存储结构…

大模型时代的向量数据库:原理解析和应用案例

大家好&#xff0c;在人工智能领域&#xff0c;数据处理和加工的需求愈发增加。随着人们深入探索AI高级的应用&#xff0c;如图像识别、语音搜索和推荐引擎等&#xff0c;数据的复杂性也在不断地增加。此时传统的数据库存储方式已不能完全满足需求&#xff0c;向量数据库应运而…

《出海和跨境:明道云HAP支撑全球化业务的能力白皮书》正式发布

随着全球化进程的加速&#xff0c;越来越多的企业开始寻求海外市场的拓展机会。然而在出海道路上&#xff0c;企业面临着诸多挑战&#xff0c;比如跨时区的协作困难、文化差异、信息异步、技术障碍等。 明道云HAP作为一款前沿的企业软件产品&#xff0c;致力于赋能企业跨境经营…

Jwt 报错 : Cannot resolve method ‘parseClaimsJws‘ in ‘JwtParserBuilder‘

Java 环境 Java 版本&#xff1a; jkd11 jwt依赖 <dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.12.5</version></dependency>报错如下图所示 解决方法 在pom.xml中把 jjwt 的依…

2024年【安全员-C证】考试及安全员-C证考试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 安全员-C证考试根据新安全员-C证考试大纲要求&#xff0c;安全生产模拟考试一点通将安全员-C证模拟考试试题进行汇编&#xff0c;组成一套安全员-C证全真模拟考试试题&#xff0c;学员可通过安全员-C证考试题全真模拟…

【MySQL】数据库--基础

目录 一、概念&#xff1a; 二、连接数据库[Dos命令] 三、SQL 语句分类 一、概念&#xff1a; MySQL 是一种开源的关系数据库管理系统 (RDBMS)数据库-表的本质仍然是文件 二、连接数据库[Dos命令] mysql -h&#xff1a;mysql服务的主机&#xff08;默认连接到本机服务器&…

2024.3.26学习笔记

今日学习韩顺平java0200_韩顺平Java_对象机制练习_哔哩哔哩_bilibili 今日学习p273-p285 包 包的本质实际上就是创建不同的文件夹/目录来保存类文件 包的三大作用 区分相同名字的类 当类很多时&#xff0c;可以很好的管理类 控制访问范围 包的基本语法 package com.xx…

第九届蓝桥杯大赛个人赛省赛(软件类)真题C 语言 A 组-分数

solution1 直观上的分数处理 #include <iostream> using namespace std; int main() {printf("1048575/524288");return 0; }#include<stdio.h> #include<math.h> typedef long long ll; struct fraction{ll up, down; }; ll gcd(ll a, ll b){if…