目录
一、数据库
命名时必须以字母开头,可以使用数字、字母、$、_ 、#组合。
创表需要指定字符集,可以配置 /etc/my.cnf 之后默认都是utf8mb4,如下配置后重启数据库,或者创表时设置字符集
1、创建数据库
mysql> create database 数据库名;
设置指定字符集
mysql> create database 数据库名
-> default character set utf8mb4;
Query OK, 1 row affected (0.00 sec)
2、切换(进入数据库)
mysql> use 数据库名 Database changed
3、删除数据库
mysql> drop database 数据库名;
Query OK, 0 rows affected (0.04 sec)
4、查看当前是哪个用户登录数据库
select user()
5、查看有哪些数据库
也可以进行模糊查询比如使用like %或者 _
mysql> show databases;
二、数据库表
1、查看表
查看有哪些表
mysql> show tables;
查看某一个表
mysql> show create table 表名;
或者
mysql> desc 表名;
也可以进行模糊查询比如使用like %或者 _
2、创建表
create table 表名(
列名 列类型,
……,
列名 列类型 );
eg1
create table test(name char(12),weig float(3,1),age int);
3、删除表
mysql> drop table 表名;
4、修改表的结构
4.1修改表的列类型
alter table 表名 modify 列名 列类型;
eg:
mysql> alter table test modify name char(8);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
4.2增加新的一列
alter table 表名 add 列名 列类型;
eg1:直接添加
mysql> alter table test add sex enum('m','f');
Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
eg2:添加在最开始
mysql> alter table test add sex enum('m','f') first;
eg3:添加在某条之后
mysql> alter table test add hobby set('dance','sing','run') after age;
Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
注意:没有before用法
4.3删除一列
alter table 表名 drop 列名;
eg:
mysql> alter table test drop hobby;
Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0
4.4列改名
alter table 表名 change 旧列名 新列名 列类型;
4.5更改表名
alter table 表名 rename 新表名;
rename table 表名 to 新表名;
eg:
mysql> alter table test rename test1;
Query OK, 0 rows affected (0.01 sec)
mysql> rename table test1 to test;
Query OK, 0 rows affected (0.00 sec)
5、复制表的结构
5.1只复制表不会复制表内数据
mysql> create table 新表 like 旧表
eg:
mysql> create table test1 like test ;
Query OK, 0 rows affected (0.00 sec)
5.2复制表及表内数据
create table 新表 select * from 旧表
eg:mysql> create table test2
-> select * from test;
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0
6、表的约束
大部分数据库支持下面五类完整性约束:
NOT NULL非空
UNIQUE Key唯一键
PRIMARY KEY主键
FOREIGN KEY外键
CHECK检查
mysql> create table student (
-> sno int primary key AUTO_INCREMENT,
#这里sno设置为主键 并且设置了自增长
-> name char(5) not null
-> );
#name设置为非空
create table student (sno int primary key,name char(5) not null);
#创建用户、删除用户
创建
#这里的地址可以是‘网络段’或者是‘localhost’等
CREATE USER 用户名@'地址' IDENTIFIED BY ‘密码’;
eg:mysql> create user jack@'192.168.157.%' identified by 'Jack@123';
Query OK, 0 rows affected (0.00 sec)
删除
drop user 用户名;
eg:mysql> drop user jack@'192.168.157.%'
-> ;
Query OK, 0 rows affected (0.00 sec)
7、授权
权限有 all、select、update、insert、delect
第一个'*'可写数据库名或者*,第二个'*'为库表名或者*,
grant 权限 on *.* to 用户名@'地址';
8、收回权限
revoke 权限 on *.* from 用户名@'地址';