文章目录
想进一步学习mysql的查询语句可以 点击这里
命令行连接
数据库操作
-
查看所有数据库
- show databases;
-
使用数据库
- use 数据库名;
-
查看当前使用的数据库
- select database();
-
创建数据库
- create database 数据库名 charset=utf8;
例:create database python charset=utf8;
- create database 数据库名 charset=utf8;
-
删除数据库
- drop database 数据库名;
例:drop database python;
- drop database 数据库名;
数据表
auto_increment表示自动增长
CREATE TABLE table_name(
column1 datatype contrai,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY(one or more columns)
);
- 例1:
-- 创建班级表
create table classes(
id int unsigned auto_increment primary key not null,
name varchar(10)
);
例2:创建学生表
create table students(
id int unsigned primary key auto_increment not null,
name varchar(20) default '',
age tinyint unsigned default 0,
height decimal(5,2),
gender enum('男','女','人妖','保密'),
cls_id int unsigned default 0
)
修改表
-
修改表-添加字段
- alter table 表名 add 列名 类型;
例:alter table students add birthday datetime;
- alter table 表名 add 列名 类型;
-
修改表-修改字段:重命名版
- alter table 表名 change 原名 新名 类型及约束;
例:alter table students change birthday birth datetime not null;
- alter table 表名 change 原名 新名 类型及约束;
-
修改表-修改字段:不重命名版
- alter table 表名 modify 列名 类型及约束;
- 例 alter table students modify birth date not null;
-
修改表-删除字段
- alter table 表名 drop 列名;
例:alter table students drop birthday;
- alter table 表名 drop 列名;
删除表
- drop table 表名;
例: - drop table students;
查看表的创建语句
- show create table 表名;
- 例: show create table classes;
增删改查(curd)
-
curd的解释: 代表创建(Create)、更新(Update)、读取(Retrieve)和删除(Delete)
-
查询基本使用
查询所有列
select * from 表名;
例:select * from classes; -
查询指定列
-
可以使用as为列或表指定别名
-
select 列1,列2,… from 表名;
-
例:select id,name from classes;
-
增加
格式:INSERT [INTO] tb_name [(col_name,…)] {VALUES | VALUE} ({expr | DEFAULT},…),(…),…
-
说明:主键列是自动增长,但是在全列插入时需要占位,通常使用0或者 default 或者 null 来占位,插入成功后以实际数据为准
全列插入:值的顺序与表中字段的顺序对应 -
insert into 表名 values(…)
-
例:insert into students values(0,’郭靖‘,1,‘蒙古’,‘2016-1-2’);
部分列插入:值的顺序与给出的列顺序对应 -
insert into 表名(列1,…) values(值1,…)
-
例:insert into students(name,hometown,birthday) values(‘黄蓉’,‘桃花岛’,‘2016-3-2’);
-
上面的语句一次可以向表中插入一行数据,还可以一次性插入多行数据,这样可以减少与数据库的通信
-
全列多行插入:值的顺序与给出的列顺序对应
-
insert into 表名 values(…),(…)…;
-
例:insert into classes values(0,‘python1’),(0,‘python2’);
-
insert into 表名(列1,…) values(值1,…),(值1,…)…;
-
例:insert into students(name) values(‘杨康’),(‘杨过’),(‘小龙女’);
-
修改
-
格式: UPDATE tbname SET col1={expr1|DEFAULT} [,col2={expr2|default}][where 条件判断]
-
update 表名 set 列1=值1,列2=值2… where 条件
-
例:update students set gender=0,hometown=‘北京’ where id=5;
删除
-
DELETE FROM tbname [where 条件判断]
-
delete from 表名 where 条件
-
例:delete from students where id=5;
-
逻辑删除,本质就是修改操作
-
update students set isdelete=1 where id=1;