mysql基础

数据库软件对大小写不敏感,需要在每条命令末尾添加‘;’

一、库操作

1. 登录数据库

  • mysql -u root -p
    -u指定用户,-p指定使用密码登录

2. 创建数据库

  • create database 数据库名称;

    创建一个数据库,名称为student :

create database student

3. 查看已有数据库

  • show databases;
    mysql基础_第1张图片

4. 删除数据库

  • drop database 数据库名称;
    例如:
drop database student

(友情提醒,谨慎操作)

5. 选择数据库

  • use 数据库名称;
    在确定使用某个数据库后,使用use (数据库名称)切换到目的数据库
use student

二、表操作

1. 新建表

create table 表名称 (
    字段名称 数据类型 [具体要求],
    ......
);

example:
create table info (
    ID int(8) not null primary key,
    name varchar(20),
    sex varchar(4),
    birthday date
);

mysql基础_第2张图片

名称 介绍
NULL 数据列可包含NULL值;
NOT NULL 数据列不允许包含NULL值;
DEFAULT 默认值;
PRIMARY KEY 主键;
AUTO_INCREMENT 自动递增,适用于整数类型;
UNSIGNED 是指数值类型只能为正数;
CHARACTER SET name 指定一个字符集;
COMMENT 对表或者字段说明;

2. 查看表

  • show tables;
    mysql基础_第3张图片

3. 查看表结构信息

  • describe 表名称;
    mysql基础_第4张图片

4. 删除表

  • drop table 表1, 表2, … ;
删除表 info

drop table info

5. 修改表

  • 修改表名 : rename table 原表名 to 新表名;
rename table info to stu;
  • 新增字段 : alter table 表名 add 字段名 数据类型 [列属性] [位置];
    位置表示此字段存储的位置,分为first(第一个位置)after + 字段名(指定的字段后,默认为最后一个位置)
alter table info add height int first;
alter table info add  weight int after height;

mysql基础_第5张图片

  • 修改字段 : alter table 表名 modify 字段名 数据类型 [列属性] [位置];
alter table info modify height int(8) first;

mysql基础_第6张图片

  • 重命名字段 : alter table 表名 change 原字段名 新字段名 数据类型 [列属性] [位置]
alter table info change height length int first;

mysql基础_第7张图片

  • 删除字段 : alter table 表名 drop 字段名;
alter table info drop length;
alter table info drop weight;

mysql基础_第8张图片


三、数据操作

1. 常用数据类型

类型 说明
int 整型
double 浮点型
varvhar 字符串型
date 日期,格式为yyyy-mm-dd

2. 添加行数据

  • insert into info 表名 values(值列表) [ ,(值列表) ];
insert into info values('1', 'liushall', 'boy', '2000-1-1');
insert into info values('1', 'liushall', 'boy', '2000-1-1'), ('2', 'zhangsan', 'boy', '2001-12-12');

mysql基础_第9张图片

  • 给部分字段添加数据 : insert into 表名(字段列表) values(值列表) [ ,(值列表) ];
insert into info(ID, name) values('3', 'lisi');

mysql基础_第10张图片

3. 查询数据

  • 查看全部字段信息 : select * from 表名 [ where 条件 ];
select * from info;
  • 查看部分字段信息 : select 字段名称[ ,字段名称 ] from 表名 [ where 条件 ];
select ID, name, sex from info where id != 3;

mysql基础_第11张图片

4. 更新数据

  • update 表名 set 字段 = 修改后的值 [where 条件];
update info set sex = 'girl' where name = 'lisi';

mysql基础_第12张图片

5. 删除数据

  • delete from 表名 [ where 条件 ];
delete from info where name = 'lisi';

mysql基础_第13张图片

PS

用 [] 括起来的时可选项,不需要的可以不用写

你可能感兴趣的:(数据库)