连接
建立连接:mysql -h主机地址 -u用户名 -p密码
本地连接可省略 -h 选项: mysql -uroot -p密码
SQL语句解释
结构化查询语言(Structured Query Language),一种特殊目的的编程语言,是一种数据库查询和程序设计语言,用于存取数据以及查询、更新和管理关系数据库系统。
每条命令必须以 ; 结尾;
SQL命令关键字不区分字母大小写。
数据库操作
1.查看已有库
show databases;
2.创建库
create database 库名 [character set utf8];
eg:创建spl数据库,编码为utf8
create database spl character set utf8;
3.查看创建库的语句(字符集)
show create database 库名;
e.g. 查看spl创建方法
show create database spl;
4.查看当前所在库
select database();
5.切换库
use 库名;
e.g. 使用spl数据库
use stu;
6.删除库
drop database 库名;
e.g. 删除test数据库
drop database test;
7.库名的命名规则
数字、字母、下划线,但不能使用纯数字
库名区分字母大小写
不能使用特殊字符和mysql关键字
表的基本操作
1.创建表(指定字符集)
>create table 表名(
字段名 数据类型,
字段名 数据类型,
…
字段名 数据类型
);
如果你想设置数字为无符号则加上 unsigned;
如果你不想字段为 NULL 可以设置字段的属性为 NOT NULL; 在操作数据库时如果输入该字段的数据为NULL ,就会报错;
DEFAULT 表示设置一个字段的默认值;
AUTO_INCREMENT定义列为自增的属性,一般用于主键,数值会自动加1;
PRIMARY KEY关键字用于定义列为主键。主键的值不能重复。
e.g. 创建班级表
create table class_1 (
id int primary key auto_increment,
name varchar(32) not null,
age int not null,
sex enum('w','m’),
score float default 0.0
);
2.查看数据表
show tables;
3.查看已有表的字符集
show create table 表名;
4.查看表结构
desc 表名;
5.删除表
drop table 表名;
插入(insert)
(1)insert into 表名 values(值1),(值2),…;
(2)insert into 表名(字段1,…) values(值1),…;
eg:
insert into class_1 values (1,'Baron',10,'m',91),(2,'Jame',9,'m',90);
查询
(1)select * from 表名 [where 条件];
(2)select 字段1,字段名2 from 表名 [where 条件];
select * from qur;
select name,age from qur;
where语句
select * from class_1 where age > 10;
select * from class_1 where between 5 and 10;
select * from class_1 where age in (6,12);
select * from class_1 where sex='m' and age>9;
更新表记录(update)
update 表名 set 字段1=值1,字段2=值2,… where 条件;
e.g.
update class_1 set age=11 where name='Abby’;
删除表记录(delete)
delete from 表名 where 条件;
注意:delete语句后如果不加where条件,所有记录全部清空
e.g.
delete from class_1 where name='Abby';
表字段的操作(alter)
(1)alter table 表名 执行动作;
添加字段(add)
alter table 表名 add 字段名 数据类型;
alter table 表名 add 字段名 数据类型 first;
alter table 表名 add 字段名 数据类型 after 字段名;
删除字段(drop)
alter table 表名 drop 字段名;
修改数据类型(modify)
alter table 表名 modify 字段名 新数据类型;
alter table 表名 执行动作;
修改字段名(change)
alter table 表名 change 旧字段名 新字段名 新数据类型;
表重命名(rename)
alter table 表名 rename 新表名;
e.g.
alter table interest add date Date after course;
时间类型数据
(1)时间格式
date :“YYYY-MM-DD”
time :“HH:MM:SS”
datetime :“YYYY-MM-DD HH:MM:SS”
timestamp :“YYYY-MM-DD HH:MM:SS”
注意:
datetime :不给值默认返回NULL值
timestamp :不给值默认返回系统当前时间
(2)日期时间函数
now() 返回服务器当前时间
curdate() 返回当前日期
curtime() 返回当前时间
date(date) 返回指定时间的日期
time(date) 返回指定时间的时间
(3)时间操作
查找操作
e.g.
select * from timelog where Date = "2018-07-02";
select * from timelog where Date>="2018-07-01" and Date<="2018-07-31";
日期时间运算
select * from 表名 where 字段名 运算符 (时间-interval 时间间隔单位);
- 时间间隔单位: 1 day | 2 hour | 1 minute | 2 year | 3 month
e.g.
select * from timelog where shijian > (now()-interval 1 day);
如果对我的文章喜欢,不要忘了 star follow (收藏、转发)予以支持
还有:不要忘了点赞喔
作者:fancymeng