用户方面:
1.创建用户: create user '用户名'@'主机' identified by '密码';
create user 'admin'@'localhost' identified by 'root';
2.授权: grant 权限 on 数据库名.表名 to '用户名'@'localhost' identified by '密码'
-- all privileges:所有权限 *.*:代表数据库中所有的表
grant select on *.* to 'admin'@'localhost' identified by 'root';
-- 立即生效
FLUSH PRIVILEGES;
3.撤销授权
revoke all on *.* from 'admin'@'localhost';
数据库操作:
-- 查看当前mysql服务器版本信息
select version();
-- 显示当前服务器下所有数据库
show databases;
--切换数据库
use 数据库名;
-- 查看当前连接的库:
select database();
--查看当前数据库下所有表
show tables;
创建数据库:
create database 数据库名 character set utf8;
--修改数据库
alter database 数据库名 character set utf8;
--删除一个数据库
drop database 数据库名;
通过cmd窗口登录语法:mysql -u账号 -p密码
通过cmd窗口进入到MySQL环境中后,退出:exit;
表操作:
基本的增删改查:
--创建表 if not exists:如果不存在该表就创建
create table if not exists 表名(
字段
)
--删除表
drop table if exists 表名;
--查看表结构
desc 表名;
--显示建表语句
show create table 表名;
--插入数据语句 一条语句插入多值用逗号隔开
insert into 表名(字段名1,字段名2,...) values(值1,值2,...),(值1,值2,...),...;
--删除表中数据 如果没有where条件,则清空表中数据
delete from 表名 [where 条件];
--删除表数据并将重置主键
truncate table 表名;
--更新数据
update 表名 set 字段名1=值1,... where 条件;
--查询语句
select * from 表名 [where 条件];
数据类型:
数值型 | |
int | 4字节 |
bigint | 8字节 |
float | 4字节 |
double | 8字节 |
tinyint | 1字节 |
时间型 | |
类型 | 格式 |
date | YYYY-MM-DD |
time | HH:mm:ss |
year | YYYY |
datetime | YYYY-MM-DD HH:mm:ss |
字符串型 | |
类型 | 描述 |
char | 定长字符串 |
varchar | 变长字符串 |
text | 长文本数据 |
longtext | 极大文本数据 |
修改表:
--对表进行重命名
rename table 表名 to 新名;
alter table 表名 rename 新名;
--更改表字段名 alter table 表名 change 原名 新名 原数据类型;
alter table student change name s_name varchar(20);
--向表中添加字段名
alter table 表名 add 字段名 数据类型;
--插入到指定位置:after->之后,first->第一列
alter table 表名 add 字段名 数据类型 after 已有字段名;
alter table 表名 add 字段名 数据类型 first;
--更改字段的数据类型
alter table 表名 modify 字段名 新数据类型;
--删除表中某一字段
alter table 表名 drop 字段名;
总结:
1.对库的增删改查: create/drop/alter/show database...
2.对表的增删改查: create/drop/alter/show table...
3.对数据的增删改查: insert/delete/update/select
注:
DDL(database define language,数据库定义语言): create/drop/alter/show
DQL(database query language, 数据库查询语言): select
DML(database manage language,数据库管理语言): insert/delete/update
DCL(database control language,数据库控制语言): 开启事务、提交事务、回滚