Fork me on GitHub

MySQL的操作(不包括数据的查询)

MySQL数据库的操作

创建数据库

1
语法: create database [if not exists] `数据库名` charset=字符的编码(utf8);

注:若创建已经存在的数据库会报错,charset后面指定数据库的字符编码

数据库名加上反引号(``),则使用关键字作为数据库名可以防止报错,并创建成功

查看数据库

1
2
3
显示所有的数据库: show databases;
显示数据库的建表语句: show create database `数据库名`;
查看当前数据库: select database();

修改数据库

只能修改数据库的字符集

1
alter database `数据库名` charset=字符集选项;

删除数据库

1
drop database [if exists] `数据库名`;

如果不使用if exists, 删除一个不存在的数据库会报错

1008 - Can't drop database '$%@'; database doesn't exist

加上 if exists:

1
2
3
drop database if exists `数据库名`;
#可以避免报错
#作用:判断指定的数据库存不存在,存在则删除.

选择数据库

选择进行操作的数据库

1
use `数据库名`;

MySQL表的操作

创建表

1
create table [if not exists] `表名`(属性)

举个栗子:

1
2
3
4
5
create table `table`(
    id int not null auto_increment  primary key comment'主键字段',
    username char(64) comment'用户名' default'root',
    password varchar(64) comment'密码'
    );

注:最后一句不能加逗号,如果加了表示没写完

约束条件(列属性):

1
2
3
4
1.null|not null   字符是否为空
2. default        默认值
3.auto_increment  自动增长
4.primary key     设为主键

给指定的数据库建表:

1
 create table 数据库名.表名(属性);

注:若使用default设置默认值,默认值不能设置中文,否则乱码

查看表

查看所有的表: show tables;

查看建表结构(建表语句): show create table 表名\G或者show create table 表名;

查看表结构: desc 表名;

删除表

1
语法:drop table [if exists] `表1`,`表2`;

修改表

  • 修改表名
1
语法: alter table `old_name` rename `new_name`;
  • 增加一个字段
1
2
3
4
5
6
7
alter table `表名` add `字段名` 数据类型;

例子1:
alter table `user` add `age` int(3) first;  #添加在表的第一个

例子2:
alter table `user` add `height` int(3) after `age`; #添加字段在指定字段的后面
  • 修改字段属性
1
alter table `表名` modify `属性名(字段名)` 数据类型;
  • 修改字段名
1
alter table `表名` change `原字段名` `新的字段名` 数据类型;
  • 修改字段位置
1
alter table `表名` change `字段名` `改为新的字段名` 数据类型 after '字段名';
  • 修改表的引擎
1
alter table `表名` engine=引擎名;
  • 移动表到指定数据库并改为指定名称
1
alter table `原表名` rename to 数据库名.表名;
  • 复制表
1
2
3
4
5
create table `新表` select * from `原来的表`;

特点:
1.旧表的数据会一起复制过来到新表中
2.不能复制主键
1
2
3
4
5
create table `新表` like `原来的表`;

特点:
1.它可以复制主键
2.但是不会复制数据

MySQL数据的操作

插入数据

1
2
3
4
5
# 插入一条
insert into 表名(字段名) values(值)

插入多条
insert into 表名(字段名) values(值1),(值2)......

插入值的数量应与表名后的字段名相对应

若插入所有的字段,则表名后的字段名可以省略

自动增长的字段可以省略,也可设置为0

md5可以在mysql中直接加密

1
md5(123456) --->e10adc3949ba59abbe56e057f20f883e

修改数据

1
update 表名 set 字段名='值' where 字段(一般使用主键)=值;

where用于匹配数据

删除数据

1
2
3
4
5
6
7
8
# 删除一条数据
delete from 表名 where 字段(一般为主键)=值;

# 删除全部数据
delete from 表名 where True;

# 记录原来的建表语句,删除整个表,数据全被清空
truncate 表名;