show databases; #显示所有的数据库
create database db1; #创建数据库
use db1; #进入数据库
show tables; #查看数据库中所有的表
# 创建表
create table tb1(
age int,
name char(10)
)
# 查看表里的内容
select * from tb1;
# 表内插入数据
insert into tb1(nid,name) values(1,'ming')
#innodb引擎:支持数据回滚(当事务出错时恢复原来状态)
#数据类型
数字:
整数
小数,
decimal,精确
float,double,非精确
字符串(一般用定长):
定长:
char(10),最大225个字符,10位是固定的,但查询效率较高,
变长:
varchar(10),最大225个字符,根据输入来确定
日期类型
#连接表
A left join B on a.xx=b.xxx
#以A为主
#将A中的所有数据罗列,而B只显示于A相应的数据
A right join B on a.xx=b.xxx
A inner join B on a.xx=b.xxx
#B只显示有跟A有关系的数据
#注入
使用pysql的execute('select name from tb1 %s'(name)),内部帮我们做了字符处理,防注入
#视图
虚拟表,修改真实表时会自动帮我们修改更新视图的结果
#存储过程(与函数有区别)
-- 创建存储过程
-- create procedure proc_1()
-- begin
-- select * from proc;
-- end
-- 执行存储过程
-- call proc_1;
-- 删除存储过程
-- drop procedure if exists proc_1;
-- create procedure proc_1(
-- -- 形参
-- in i1 int
-- )
-- begin
--
-- declare d1 int;
-- -- 定义变量,默认值为3
-- declare d2 int default 3;
-- set d1 = i1+d2;
-- select * from proc;
-- end
-- 如果在命令行输入,需要使用delimiter $$ 把结束符;设置成别的符号(这里是$$),执行完后再改回来delimiter ;
-- delimiter $$
-- create procedure proc_2(
-- in i1 int
-- )
-- begin
-- declare d1 int;
-- declare d2 int default 3;
-- set d1 = i1+d2;
-- select * from proc;
-- end $$
-- delimiter ;
-- in,out,inout
create procedure proc_3(
in i1 int, -- in 是传入参数
out i2 int, -- out 是返回参数
inout i3 int -- inout 既传入又返回
)
begin
declare d2 int default 3; -- 定义要放在首行
set i3=i3+1;
select * from proc;
-- 将查询的值存储到d2中
select id into d2 form proc where mid=5;
select name from man where nid = d2;
if i1 = 1 then
set i2 = 100+d2;
elseif i1 = 2 then
set i2 = 200+d2;
else
set i2 = 300+d2;
end if;
end
-- 在MySQL中执行存储过程
set @u = 5;
-- 这里的@q是out的返回值,@u是inout的返回值
call proc_3(1,@q,@u);
select @q,@u;
#存储过程可以拿到:
1.SQL的结果集(select语句)
2.out,inout的返回值
#触发器
-- 触发器,before insert,在插入数据前触发
create trigger tri_before_insert_part before insert on part for each row
begin
-- 如果插入的caption=1,则把新增的caption值添加到person表中的part_id
if new.caption = 1 then
insert into person(part_id) values(new.caption);
end if;
end
insert into part(caption) values (1);
1.before/after inset/delete/update
2.新插入的数据时new,删除的数据是old,update都可以用
# 函数
-- 获取长度
select char_length("字符长度"),length("字节长度");
-- 字符串拼接
select CONCAT("字符串","拼接"),CONCAT_WS("_","下划线","拼接");
-- 字符串替换 x666
select insert("xiao",2,3,666)
-- 自定义函数
create function f1(
a1 int,
a2 int
)
returns int -- 两个参数,所以是returns
begin
declare num int;
set num = a1+a2;
return(num);
end
select f1(11,id),id from proc;
-- 函数与存储过程的区别,函数不能在里面返回结果集(即不能再里面写select 语句,其他SQL语句可以)