当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql存储过程学习笔记--建立简单的存储过程

Mysql存储过程学习笔记--建立简单的存储过程

2017年12月12日  | 移动技术网IT编程  | 我要评论

重庆护士门下载,春运返程高峰,南郭先生与狼

一、存储过程

  存储过程(stored procedure)是在大型数据库系统中,一组为了完成特定功能的sql语句集,经编译后存储在数据库中,用户
通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。而我们常用的操作数据库语言sql语句在执行的时
候需要要先编译,然后执行,所以执行的效率没有存储过程高。

  存储过程优点如下:

重复使用。存储过程可以重复使用,从而可以减少数据库开发人员的工作量。提高性能。存储过程在创建的时候在进行了编译,将来使用的时候不再重新翻译。一般的sql语句每执行一次就需要编译一次,所以使用存储过程提高了效率。减少网络流量。存储过程位于服务器上,调用的时候只需要传递存储过程的名称以及参数就可以了,因此降低了网络传输的数据量。安全性。参数化的存储过程可以防止sql注入式攻击,而且可以将grant、deny以及revoke权限应用于存储过程。

  存储过程简单语法:

create procedure 存储过程名称(
  输入输出类型 变量名称 类型,

    输入输出类型 变量名称 类型

)
begin
  -- 声明, 语句要完成的操作,增删改查。。。
end

二、实例

  例子中的存储过程均使用mysql作为例子。
  表结构如下:

drop table if exists `person`;
create table `person` (
  `id` int(11) not null auto_increment,
  `username` varchar(255) default null,
  `age` int(11) default null,
  `password` varchar(255) default null,
  primary key (`id`)
) engine=innodb auto_increment=11 default charset=utf8;

  1、只带in(输入参数)的存储过程

   表示该参数的值必须在调用存储过程时指定,在存储过程中修改该参数的值不能被返回,为默认值.

drop procedure if exists proc_person_findbyid;
-- 创建存储过程
create procedure proc_person_findbyid(
    in n int
)
begin
     select * from person where id=n;
end
-- 定义变量
set @n=2;
-- 调用存储过程
call proc_person_findbyid(@n);

 调用结果如下:

  2、只带out(输出参数)的存储过程

  该值可在存储过程内部被改变,并可返回。

drop procedure if exists proc_person_getcount
-- 创建存储过程
create procedure proc_person_getcount(
    out n int(11)
)
begin
     select count(*) into n from person ;
end
-- 调用存储过程
call proc_person_getcount(@n);
select @n as '总数';

 调用结果如下:

 

  3、带in(输入参数)和out(输出参数)的

  调用时指定,并且可被改变和返回

drop procedure if exists proc_person_findinfobyid; 
-- 创建存储过程
create procedure proc_person_findinfobyid(
    in n int(11),
    out pusername varchar(255),
    out page int(11)
)
begin
     select username, age into pusername, page from person where id=n;
end
-- 定义变量
set @id=2;
-- 调用存储过程
call proc_person_findinfobyid(@id,@username, @age);
select @username as '用户名', @age '年龄';

 调用结果如下:

  

  4、带inout(输入输出)参数的存储过程

-- 输入输出drop procedure if exists proc_person_get_age;-- 创建存储过程create procedure proc_person_get_age(  inout n int(11))begin   select age into n from person where id=n;endset @id = 1;call proc_person_get_age(@id); select @id;

  调用结果如下:

 

  5、 关于输入输出参数

in为输入, 定义参数时,可以不加,不加则默认为输入参数。out为输出,定义参数时,必须加上。inout为输入和输出,必须加上。表示该参数可以输入也可在处理后存放结果进行输出。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网