🎽操作数据库表
2021-4-7
| 2022-9-1
0  |  0 分钟
type
status
date
slug
summary
tags
category
icon
password
URL
Sep 1, 2022 09:23 AM
操作数据库:CRUD(Create Retrieve Update Delete)
create database dbname;
create database if not exists db1;
create database db2 character set gbk;
create database if not exists db3 character set gbk;
show databases;
show create database dbname;
alter database db2 character set uft8;
drop database db2;
drop database if exists db2;
 
使用数据库
select database();
use db1;
操作表
C 创建
create table tablename(
id int,
name varchar(32),
age int,
score double(4,1),
birthday date,
insert_time timestamp
);
复制:create table stu like student;
注意:最后一列不需要加逗号
数据库类型:
  1. int:整数类型,如age
  1. double:小数类型,如score
  1. date:日期,只包含年月日,yyyy-MM-dd
  1. datetime:日期,包含年月日时分秒,yyyy-MM-dd HH:mm:ss
  1. timestamp:时间戳类型,包含年月日时分秒,yyyy-MM-dd HH:mm:ss
  1. varchar:字符串,如name varchar(20):姓名最大二十个字符
 
R 查询
show tables;
desc tablename;
U 修改
  1. 修改表名
    1. alter table tablename rename to newtablename;
  1. 修改表的字符集
    1. alter table tablename character set utf8;
  1. 添加一列
    1. alter table tablename add column int;
  1. 修改列名称 类型
    1. alter table tablename change columnname newcolumanname newdatatype;
    2. alter table tablename modify columnname newdatatype;
  1. 删除列
    1. alter table tablename drop columnname;
D 删除
drop table tablename;
drop table if exists tablename;
 
 
客户端图形化工具:SQLYog,DBeaver,WorkBench
 
DML:增删改表中数据
添加数据
语法:
insert into 表名(列名1,列名2,列名3) values(值1,值2,值3);
注意:
  1. 列名和值要一一对应
  1. 如果表名后,不定义列名,则默认给所有列添加值
  1. 除了数字类型,其她类型需要使用引号(单双引都可以)
删除数据
语法:
delete from 表名 where 条件;
delete from 表名;(不推荐,效率低)
truncate table 表名;(删除表,再重新创建一张一样的空表)
💡
workbench删除需要更新safe update为0
💡
SET SQL_SAFE_UPDATES = 0;
修改数据
语法:
update student set age=22 where id =1;
如果不加任何条件,则会将表中的所有记录全部修改;
DQL:查询表中的记录
  • select * from 表名;
 
  1. 语法:
    1. select 字段列表
    2. from 表名列表
    3. where 条件列表
    4. group by 分组字段
    5. having 分组之后的条件
    6. order by 排序
    7. limit 分页限定
基础查询
  1. 多个字段的查询
    1. select 字段1,字段2,字段3,from 表名;
  1. 去除重复
    1. distinct
  1. 计算列
    1. 一般可以使用四则运算计算一些列的值。(一般只会进行数值型的计算)
    2. ifnull(表达式1,表达式2)
      1. 表达式1:那个字段需要判断是否为null
      2. 如果该字段为null后的替换值
  1. 起别名
    1. as: as也可以省略
条件查询
  1. < > <=
  1. between and
  1. in
  1. like
    1. _:单个任意字符
    2. %:多个任意字符
  1. is null
  1. and
  1. or
  1. not
 
例子:
select * from student where age>=20;
select * from student where age>=20 and age <=30;
select * from student where age between 20 and 30;
select * from student where age =22 or age =19 or age = 25;
select * from student where age in (22,18,25);
select * from student where english is null;
select * from student where english is not null;
select * from student where name like "zhao%";
select * from student where name like "____li%";
select * from student where name like "____";
select * from student where name like "%zhao%";
 
 
学习思考
  • database
  • 数据库连接池多表查询
    • Valine
    • Cusdis
    目录