【MySQL】数据库笔记

2019-08-12  本文已影响0人  感同身受_

每个语句后面加;或/g

  1. mysql -u root -p+密码;
    连接服务器
  2. use + 库名;
    连接库
  3. show databases;
    如果不知道有哪些库,想查看一下
  4. show tables;
    选完库之后,面对的是表,查看库下面的全部表
  5. create database 数据库[charset 字符集];
    自己创建一个库,如create database gy1 charset utf8;
  6. drop database 表名;
    删除一个数据库,如:drop database gy1;
  7. rename
    把数据库改名,表/列可以改名,database不能改
    表改名:rename table stu to newstu;

表操作

  1. create table stu(
    snum int,
    sname varchar(10)
    )engine myisam charset utf8;
    创建表
  2. SHOW VARIABLES LIKE 'datadir';
    输入命令,返回数据库文件保存路径
  3. drop table 表名;
    删除一张表
  4. rename table stu to newstu;
    改表名
  5. insert into stu values
    (1,'zhangsan'),
    (2,'lisi'),
    (3,'wangwu');
  6. truncate stu;
    清空表数据
  7. select * from stu;
    查看表数据
  8. trubcate 和 delete区别:
    truncate相当于删表再重建一张同样的表格,操作后得到一张全新的表
    而delete是从删除所有的层面来操作的
    truncate相当于把旧的学籍表扔了重画一张
    delete相当于用橡皮把学籍表的数据给擦掉
    如果决定全部清空的话,truncate速度更快一些

常见问题

命令行属性,使用的是GBK编码,所以需要告诉客户端,我使用的是GBK编码:
set names gbk;
再使用查表语句select * from stu;

;是命令行的结束语句

当输入命令成了

mysql>show database
    ->

时,可以使用\c结束

最基本的增删改查

  1. tee D:\xxx.sql
    这句话是把自己写的sql和结果都输出到一个sql文件里,便于自己复习
mysql> create table class(
    //primary自增型
    -> id int primary key auto_increment,
    -> sname varchar(10) not null default '',
    -> gender char(1) not null default '',
    -> company varchar(20) not null default '',
    -> salary decimal(6,2) not null default 0.00,
    //注:此句末尾没有逗号
    -> fanbu smallint not null default 0
    -> )engine myisam charset utf8;


create table class(
id int primary key auto_increment,
sname varchar(10) not null default '',
gender char(1) not null default '',
company varchar(20) not null default '',
salary decimal(6,2) not null default 0.00,
fanbu smallint not null default 0
)engine myisam charset utf8;
  1. desc classl;
    查看表的结构

一、增:insert

添加表的口诀:
“往哪张表添加行,
给哪几行添加值,
分别是什么值”

【注】若是插入的数据中含有中文,要先使用set names gbk;

//要先执行   set names gbk;
insert into class
(id,sname,gender,company,salary,fanbu)
values
(1,'张三','男','百度',8888.67,234);

//以上语句是插入所有列,可以不声明待插入的列,此时,会默认插入所有的列,所以,可简写为
insert into class
values
(1,'张三','男','百度',8888.67,234);



//部分信息插入
insert into class
(sname,gender,salary)
values
('张三','男',8844.67);

//多行插入
insert into class
(sname,company,salary)
values
('刘备','皇室',54.26),
('孙策','江东',12.35),
('曹操','宦官后裔',156.21);

【注】列与值按顺序一一对应,

改:update

口诀:
改哪张表
改哪几列的值
分别改为什么值
在哪些行生效

mysql> update class
    -> set fanbu=123
    -> where id = 6;

//where expression,表达式
//只要where表达式为真,则该行就发挥作用
//需要同时满足的条件之间用and连接
//where=1 所有的行都要被改掉,因为1恒为真,每一行都要改
update class
set fanbu=123
where id = 6;

删:delete

删除是指删除整行,不存在删除某一行的一列
口诀:
你要删哪张表的数据
你要删掉哪些行
delete from class where sname='张三';

查:select

口诀:
查哪张表的数据
查哪几列
查哪一行

//查所有行所有列,*代表所有列,表明后面不加where,默认为全部行
select * from class;

//部分列,所有行
select sname,salary from class;

//查id>3 的所有列
select * from class where id>3;

//取id<5的人,取其姓名和饭补
select sname,fanbu from class where id<5;

连接字符串:concat

上一篇 下一篇

猜你喜欢

热点阅读