一、昨日内容回顾
1.单表查询
优先级
from
where
group by
having
select
distinct
order by
limit
2 . 多表查询
inner join。。。on
left join 。。。on
rigth join 。。。on
二、今日内容总结
1.pymysql
(1) 建立连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='practice',charset='utf8')
(2)实例化游标
cursor = conn.cursor() # 里边可以传参cursor=pymsql.cursors.DictCursor
(3) 定义sql语句
(4) cursor.excute(sql)
cursor.excutemany(sql,[(1,'a'),(2,'b')]) # 返回值为操作成功影响行数
(5) 取值
cursor.fetone()
cursor.fetall()
cursor.fetmany()
(6) 调游标位置
cursor.scroll(1,mode='relative')
cursor.scroll(1,mode='absolute')
(7) cursor.close()
conn.close()
2.视图
create view 视图名 as select XXX from xxx。。。
alter view 视图名 as select 。。。。
drop view 视图名 。。。。。
3.触发器 insert(new),delete(old),update(new,old)
create trigger 触发器名 before insert on 表名
for each row
begin
。。。。
end
create trigger t1 after insert on user for each row set new.name = Upper(new.name);
create table del_info(del_name varchar(32),del_time datetime); create trigger t_del before delete on user for each row begin insert into del_info values(old.name,now()); end
4.函数
1) 一堆内置函数
重点:
date_formart(日期,‘%Y-%m’) 。。。。。。
2) 自定义函数
create function myfunc(a int,b int) returns int begin declare c int; set c=a+b; return c; end;
删除函数
drop function myfunc
执行函数
select myfunc(1,2)
5. 存储过程
create table product( id int primary key, name varchar(32) not null, price int ); insert into product values(1,'apple',18),(2,'banana',6); create procedure productprice( out pmax decimal(8,2), out pmin decimal(8,2), out pavg decimal(8,2) ) begin select Max(price) into pmax from product; select Min(price) into pmin from product; select Avg(price) into pavg from product; end; call productprice(@pmax,@pmin,@pavg);
6.游标
create procedure riseinprice( in percent decimal(4,2)) begin declare o int; declare name varchar(32); declare done boolean default 0; declare riseprice CURSOR for select id from product; declare continue handler for sqlstate '02000' set done=1; open riseprice; repeat fetch riseprice into o; update product set price=50 where id = o; until done END repeat; close riseprice; end;
7 事务
start transaction:
.....
.....
savepoint delete1
.....
commit/rollback/rollback to delete1