MySQL所使用的SQL语言是用于访问数据库的最常用标准化语言。所有的数据都是以文件的形式存放在数据库目录/var/lib/mysql下。
一、SQL命令的使用规则
1、每条SQL命令必须以 ; 结尾
2、SQL命令不区分字母大小写
3、使用 \c 终止当前命令的执行
二、库的管理
1、库的基本操作
a、查看已有的库show databases;
b、创建库
create database 库名 ;
create database 库名 default charset=utf8;
create database 库名 character set utf8;
c、查看创建库的语句(字符集)
show create database 库名;
d、查看当前所在库
select database();
e、切换库
use 库名;
f、查看库中已有表
show tables;
g、删除库
drop database 库名;
2、库的命名规则
a、数字、字母、_,但是 不能是纯数字b、库名区分字母大小写
c、不能使用特殊字符和mysql关键字
3、示例
1、创建库testdb,指定字符集为utf8
create database testdb character set utf8;
2、进入到库 testdb
use testdb;
3、查看当前所在库
select database();
4、创建库 testdb2,指定字符集为 latin1
create database testdb2 character set latin1;
5、进入到库 testdb2
use testdb2;
6、查看 testdb2 的字符集
show create database testdb2;
7、删除库 testdb
drop database testdb;
8、删除库 testdb2
drop database testdb2;
show databases;
三、表的管理
1、表的基本操作
a、创建表(指定字符集)create table 表名(
字段名1 数据类型,
字段名2 数据类型,
字段名3 数据类型
);
create table 表名(
字段名1 数据类型,
字段名2 数据类型,
字段名3 数据类型
)character set utf8;
b、查看创建表的语句(字符集)
show create table 表名;
c、查看表结构
desc 表名;
d、查看所有表
show tables;
e、删除表
drop table 表名;
2、表的命名规则(同库的命名规则)
3、示例
1、创建库 python1
create database python1;
2、在python1库中创建表 pymysql,并指定字符集为 utf8字段有三个:id name age 数据类型自己定义(比如说:char(20) 、int )
use python1;
create table pymysql(
id int,
name char(20),
age int
);
3、查看创建表 pymysql 的语句
show create table pymysql;
4、查看pymysql的表结构
desc pymysql;
5、删除表 pymysql
drop table pymysql;
6、删除库 python1
drop database python1;
四、表记录的管理
1、在表中插入记录
insert into 表名 values(值1),(值2),(值3),...;insert into 表名(字段名1,字段名2) values(),(),...;
2、查询表记录
select * from 表名 [where 条件];select 字段名1,字段名2 from 表名 [where 条件];
3、删除表记录(delete)
delete from 表名 where 条件;注意:
delete语句后没有加where条件,表中所有记录全部清除
4、更新表记录(update)
update 表名 set 字段1=值1,字段2=值2,... where 条件;注意
update语句后面如果不加where条件子句,会将表中所有记录全部更改
5、示例
1、查看所有库
show databases;
2、创建一个新库 studb
create database studb;
3、在 studb 中创建一张表tab1,指定字符集utf8,字段有:id name age score 四个 char(15)
use studb;
select database();
create table tab1(
id int,
name char(15),
age int,
score int
)character set utf8;
4、查看 tab1 的表结构
desc tab1;
5、在tab1中随便插入2条记录
insert into tab1 values(1,"李白",30,90),(2,"杜甫",30,88);
6、在tab1中的name和score两个字段插入2条记录
insert into tab1(name,score) values("李清照",25),("王维",28);
7、查看tab1表中所有记录
select * from tab1;
8、查看tab1表中所有人的名字和成绩(score)
select name,score from tab1;
1、查找所有蜀国人信息
select * from hero where country="蜀国";
2、把id为2的英雄名字改为司马懿,国家改为魏国
update hero set name="司马懿",country="魏国" where id=2;
3、查找女英雄的姓名、性别和国家
select name,sex,country from hero where sex="女";
4、删除所有魏国的英雄
delete from hero where country="魏国";
5、查找所有蜀国男英雄的信息
select * from hero where country="蜀国" and sex="男";
6、删除所有的英雄
delete from hero;
五、表字段的操作
语法:alter table 表名 执行动作;1、添加字段(add)
alter table 表名 add 字段名 数据类型 ;alter table 表名 add 字段名 数据类型 first; 插在第一列
alter table 表名 add 字段名 数据类型 after 字段名1;插在字段名1后
2、删除字段(drop)
alter table 表名 drop 字段名;3、修改字段数据类型(modify)
alter table 表名 modify 字段名 新数据类型;注意:修改数据类型是会受到表中原有数据的限制