MySQL存储过程

MySQL存储过程

返回首页

1、MySQL存储过程

存储过程就是保存在MySQL上的一个别名,这个别名代指的是一些SQL语句。

使用别名就可以查到结果。

2、存储过程的语法:create procedure 别名()

delimiter //
create procedure p1()
bing
    select * from student;
    insert into teacher(tname) values('geroge');
end //
delimiter ;

3、视图的别名调用是当做一张表来调用,而存储过程的别名是当做一个函数一样调用。

   存储过程的别名是用来代替程序员写SQL语句的。

4、存储过程的调用:call p1(); 

5、pymysql调用方法:cursor.callproc('p1') 这样就可以执行p1了。

           拿到callproc('p1') 的结果用result = cursor.fetchall() 

6、给存储过程传参数:

  传参数必须加关键字:in、out、inout

delimiter //
create procedure p2(
  in n1 int,
  in n2 int ) bing select
* from student where id>n1; insert into teacher(tname) values('geroge'); end // delimiter ;

call p2(12,2)
cursor.callproc('p2',(12,2)) #在pymysql中,调用有参数的存储过程p2。

   out的用法:可以拿到返回集。

delimiter //
create procedure p2(
  in n1 int,
  out n2 int
) 
bing
    select * from student where id>n1;
    set n2 = 123123;
end //
delimiter ;


set @v1 = 0;
call p2(12,@v1)
select @v1;

cursor.execute('select @_p2_0,@_p2_1') #在pymysql中,拿到结果集。

 7、事务

delimiter //
create procedure p3(
    out status int   
)
being
    declare exit handler for sqlexception
    being
        -- error
        set status =1;
        rollback;
    end;   

    start transaction;
        delete from tb1;
        insert into tb2(name) values('seven');
    commit;

    -- success
    set status = 2;
end //
delimiter ;
    

----- END -----

原文地址:https://www.cnblogs.com/george92/p/15092776.html