数据库常用基本操作(DDL)
1.功能
查看所有的数据库
show databases;
创建数据库
create database;
切换数据库
use mysql1;
删除数据库
drop database;
数据库常用基本操作
1.创建表
-- 1DDL操作之数据库操作 -- 查看所有数据库 SHOW DATABASES;
-- 创建数据库
CREATE DATABASE mydb1; CREATE DATABASE if not exits mydb1;
-- 选择使用哪一个数据库
use mydb1;
-- 删除数据库
DROP DATABASE mydb1;
-- 创建表 -- 选择mydb1 USE mydb1; CREATE TABLE IF NOT EXISTS student( sid INT, name VARCHAR(20), gender VARCHAR(20), age INT, birth date, address VARCHAR(20), score DOUBLE )
-- 3.查看数据库所有的表
show tables;
-- 4.查看指定表的构建语句
show create table student;
-- 5.查看表结构
desc student;
-- 6.删除表
drop table student;
--7.修改表添加列
-- 修改表结构 -- 1.添加列: alter table 表名 类型(长度) [约束]
-- 为student添加一个新的字段为:系别 dept 类型为:varchar(20)
alter table student add dept varchar(20);
--8.修改列名和类型
-- 修改列名和类型:alter table 表名 change 旧列名 新列名 类型(长度)【约束】
-- 为student表的dept字段更换为department varchar(30)
use mydb1;
alter table student change dept department varchar(30);
--9.修改表删除列
-- 修改表删除列:alter table 表名 drop 列名
-- 删除student表中的department这列
alter table student drop department;
--10.修改表名
-- 修改表名:rename table 表名 to 新表名 -- 将student表的名字改为stu rename table student to stu;
2.数值类型
DECIMAL (M,D) decimal(5,2)5表示一共5位有效数字,小数点后2位有效数字。
MYSQL数据库基本操作-DML
1.数据插入(增)
-- 1.数据的插入
格式一
insert into stu(sid,name,gender,age,birth,address,score) values(1,'张三','男',17,'2001-07-13','陕西',58.5);
多列添加
insert into stu(sid,name,gender,age,birth,address,score) values(2,'王五','男',14,'2002-07-13','陕西',58.5), (3,'李四','女',20,'2003-07-13','陕西',58.5);
格式二
insert into stu values(4,'朱博','女',20,'2003-07-13','陕西',58.5);
多列添加
insert into stu values(5,'芳芳','女',20,'2003-07-13','陕西',58.5), (5,'张华','男',20,'2003-07-13','陕西',58.5);
2.数据的修改(改)
1.全部修改
-- 将所有学生的地址改为重庆
update stu set address = '重庆';
2.条件修改
-- 将sid为4的学生该被北京
update stu set address = '上海' where sid > 4;
3.多列修改
-- 将id为5的学生的地址修改为北京,成绩修改为100
update stu set address = '北京',score = 100 where sid = 5;
3.数据删除
-- 删除数据 -- 格式:delete from 表名 [where 条件]; -- truncate table 表名 或者 truncate 表名 -- 1.删除sid为4的学生数据 delete from stu where sid = 4; -- 2.删除表所有的数据 delete from stu; -- 清空表数据 truncate stu;
练习
-- 创建表 --
USE mydb1;
-- 创建员工employee,id name gender salary
create TABLE if not exits mydb1.employee(
id INT,
name varchar(20),
gender varchar(20),
salary INT
)
-- 插入数据
insert into employee VALUES(1,'张三','男',2000),
(2,'李四','男',1000),
(3,'王五','女',4000);
-- 将所有的员工工资改为5000;
update employee set salary = 5000;
-- 将姓名为‘张三’的员工薪水修改为3000元。
update employee set salary = 3000 where name = '张三';
-- 将姓名为‘李四’的员工薪水修改为4000元,gender改为女
update employee set gender = '女',salary = 4000 where name = '李四';
-- 将王五的薪水在原有基础上增加1000
update employee set salary = salary + 1000 where name = '王五';