搜索
首页数据库mysql教程mysql存储过程开荒_MySQL

存储过程可以一次执行多条语句,处理复杂的业务逻辑,完成一些计算。
这篇博客总结一下mysql中存储过程基本的用法——mysql存储过程开荒。我们从怎么写存储过程和怎么调用两方面来探讨下:

一、mysql中存储过程的用法

注意下面的示例可以在mysql管理工具中(我用的navicat)直接运行,如果要在mysql客户端(dos窗口)需要加 delimiter$$ 分隔符。


首先来看第一个例子:
这个存储过程有两个int类型的输入参数,一个varchar类型的输出参数
在begin和end之前执行数据库操作或是计算,
用declare声明了一个int类型的变量,
后面是一个if 判断,注意后面需要有then 和end if,这才是完整的if判断
select语句进行输出,可以直接用select ‘*’输出,或是用as 添加一个列名
存储过程写好编译无误后,用call调用,这里需要一个输出参数,所以我们定义了一个@p_in变量

<code class="hljs sql">use etoak;
drop procedure if exists t1;
create procedure t1(in a int,in b int,out d varchar(30))
begin
   declare c int;
   if a is null then
      set a = 0;
   end if;
   if b is null then
      set b = 0;
   end if;
   set c = a + b;
  /* select c as sum;*/    
    select &#39;s&#39; into d;    
    select d as &#39;哈哈&#39;;    -- 输出一列
end;

/*调用存储过程*/
set @p_in = 1;
call t1(10,1,@p_in);</code>

上面我们使用if then条件判断,下面来看使用case when来完成更多的条件:

<code class="hljs sql"><code class="hljs sql">drop procedure if exists t1;
create procedure t1(in a int,in b int,out c varchar(30))
begin
    declare d int;
    set d = a+1;
    case d
        when 1 then insert into student values(null,&#39;dx&#39;,11,now());
        when 2 then insert into student values(null,&#39;aa&#39;,11,now());
        else insert into student values(null,&#39;bb&#39;,11,now());
    end case;
    select * from student;
end;</code></code>

<code class="hljs sql">再来看两个循环,一个是while do循环,一个是loop循环:

<code class="hljs sql"><code class="hljs sql"><code class="hljs vbnet">
/*使用while do循环*/
create procedure t1()
begin
    declare i int DEFAULT 0;
    while i<5 DO    
        insert into student(name) values(i);
        set i=i+1;
    end while;
    select * from student;
end;

/*使用loop循环*/
drop procedure if exists t1;
create procedure t1()
begin
    declare i int DEFAULT 0;
    loop_label:LOOP 
        if i = 3 THEN       
            set i = i + 1;
            ITERATE loop_label;    -- iterate相当于java循环里的continue
        end if;
        insert into student values(null,i,i,now());
        set i = i + 1;
        if i >= 5 THEN      
            leave loop_label;
        end if;
    end loop;
    select * from student;
end;</code></code></code>

<code class="hljs sql"><code class="hljs vbnet">还有比较常用的模糊查询:

<code class="hljs sql"><code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql">/*模糊查询*/
drop procedure if exists t1;
create procedure t1(in a varchar(30),out c varchar(30))
begin
    declare d int;
        select * from student where name like concat(&#39;%&#39;,a,&#39;%&#39;);

end;</code></code></code></code>

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql">这个例子中要注意的是使用了concat拼接字符串函数。

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql">二、在java代码中如何调用存储过程

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql">通过上面我们知道可以在mysql客户端里面通过call调用存储过程,那在java代码里面又是如何调用的呢<br> 我们来看下下面的例子,使用jdbc的方式调用带输入输出参数的存储过程:<br> 存储过程为如下,实现简单的加法:

<code class="hljs sql"><code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene">create procedure t1(in a int,in b int,out d int)
begin
   declare c int;
   if a is null then
      set a = 0;
   end if;
   if b is null then
      set b = 0;
   end if;
   set c = a + b;  
   select c into d;
end;</code></code></code></code></code>

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><strong>java中通过jdbc调用:</strong>

<code class="hljs sql"><code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java">
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;

public class TestProc {
    public static void main(String[] args) throws SQLException {
        TestProc tp = new TestProc();
        int a = tp.testPro(5, 6);
        System.out.println(a); //打印输出值
    }
    //获取数据库连接
    private static DBConnection dbConnection=null;
    static {
        if (null == dbConnection) {
            dbConnection = new DBConnection(); 
        }
    } 
    //执行存储过程的方法
    public int testPro(int a,int b) throws SQLException{
        Connection conn = null;
        CallableStatement stmt = null;
        int out = 0;
        String sql="";
        try {
            conn = dbConnection.getConnection();
            stmt = conn.prepareCall("{call t1(?,?,?) }");
            stmt.setInt(1, a);
            stmt.setInt(2, b);
            stmt.registerOutParameter(3, Types.INTEGER);
            stmt.execute();
            out = stmt.getInt(3);  //这里获取下输出参数
        }finally {
            dbConnection.close(conn);
            dbConnection.close(stmt);
        } 
        return out;
    }
}
</code></code></code></code></code></code>

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><strong>mybatis中存储过程的调用:</strong>

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java">声明接口:

<code class="hljs sql"><code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><code class="hljs lasso">public Map proc(Map map);</code></code></code></code></code></code></code>

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><code class="hljs lasso">xml:
 

<select id="proc" parameterType="map" statementType="CALLABLE">
        {call t1(
            #{firstParam,jdbcType=INTEGER,mode=IN},
            #{secondParam,jdbcType=INTEGER,mode=IN},
            #{outParam,jdbcType=INTEGER,mode=OUT}
        )}
    </select>

 

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><code class="hljs lasso"><code class="hljs cs">测试:

<code class="hljs sql"><code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><code class="hljs lasso"><code class="hljs cs"><code class="hljs vhdl">Map map = new HashMap();
        map.put("firstParam",1);
        map.put("second", 2);
        bi.proc(map);
        System.out.println(map.toString());</code></code></code></code></code></code></code></code></code>

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><code class="hljs lasso"><code class="hljs cs"><code class="hljs vhdl"><strong>这里注意一下:</strong><br> mybatis的入参map里面不需要put输出参数,执行完存储过程之后,会自动把输出参数放到map里面。所以我们的打印结果如下:

<code class="hljs sql"><code class="hljs vbnet"><code class="hljs sql"><code class="hljs oxygene"><code class="hljs java"><code class="hljs lasso"><code class="hljs cs"><code class="hljs vhdl">{second=2, firstParam=1, outParam=1}

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
MySQL的许可与其他数据库系统相比如何?MySQL的许可与其他数据库系统相比如何?Apr 25, 2025 am 12:26 AM

MySQL使用的是GPL许可证。1)GPL许可证允许自由使用、修改和分发MySQL,但修改后的分发需遵循GPL。2)商业许可证可避免公开修改,适合需要保密的商业应用。

您什么时候选择InnoDB而不是Myisam,反之亦然?您什么时候选择InnoDB而不是Myisam,反之亦然?Apr 25, 2025 am 12:22 AM

选择InnoDB而不是MyISAM的情况包括:1)需要事务支持,2)高并发环境,3)需要高数据一致性;反之,选择MyISAM的情况包括:1)主要是读操作,2)不需要事务支持。InnoDB适合需要高数据一致性和事务处理的应用,如电商平台,而MyISAM适合读密集型且无需事务的应用,如博客系统。

在MySQL中解释外键的目的。在MySQL中解释外键的目的。Apr 25, 2025 am 12:17 AM

在MySQL中,外键的作用是建立表与表之间的关系,确保数据的一致性和完整性。外键通过引用完整性检查和级联操作维护数据的有效性,使用时需注意性能优化和避免常见错误。

MySQL中有哪些不同类型的索引?MySQL中有哪些不同类型的索引?Apr 25, 2025 am 12:12 AM

MySQL中有四种主要的索引类型:B-Tree索引、哈希索引、全文索引和空间索引。1.B-Tree索引适用于范围查询、排序和分组,适合在employees表的name列上创建。2.哈希索引适用于等值查询,适合在MEMORY存储引擎的hash_table表的id列上创建。3.全文索引用于文本搜索,适合在articles表的content列上创建。4.空间索引用于地理空间查询,适合在locations表的geom列上创建。

您如何在MySQL中创建索引?您如何在MySQL中创建索引?Apr 25, 2025 am 12:06 AM

toCreateAnIndexinMysql,usethecReateIndexStatement.1)forasingLecolumn,使用“ createIndexIdx_lastNameEnemployees(lastName); 2)foracompositeIndex,使用“ createIndexIndexIndexIndexIndexDx_nameOmplayees(lastName,firstName,firstName);” 3)forauniqe instex,creationexexexexex,

MySQL与Sqlite有何不同?MySQL与Sqlite有何不同?Apr 24, 2025 am 12:12 AM

MySQL和SQLite的主要区别在于设计理念和使用场景:1.MySQL适用于大型应用和企业级解决方案,支持高性能和高并发;2.SQLite适合移动应用和桌面软件,轻量级且易于嵌入。

MySQL中的索引是什么?它们如何提高性能?MySQL中的索引是什么?它们如何提高性能?Apr 24, 2025 am 12:09 AM

MySQL中的索引是数据库表中一列或多列的有序结构,用于加速数据检索。1)索引通过减少扫描数据量提升查询速度。2)B-Tree索引利用平衡树结构,适合范围查询和排序。3)创建索引使用CREATEINDEX语句,如CREATEINDEXidx_customer_idONorders(customer_id)。4)复合索引可优化多列查询,如CREATEINDEXidx_customer_orderONorders(customer_id,order_date)。5)使用EXPLAIN分析查询计划,避

说明如何使用MySQL中的交易来确保数据一致性。说明如何使用MySQL中的交易来确保数据一致性。Apr 24, 2025 am 12:09 AM

在MySQL中使用事务可以确保数据一致性。1)通过STARTTRANSACTION开始事务,执行SQL操作后用COMMIT提交或ROLLBACK回滚。2)使用SAVEPOINT可以设置保存点,允许部分回滚。3)性能优化建议包括缩短事务时间、避免大规模查询和合理使用隔离级别。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器