search
HomeDatabaseMysql Tutorialmysql存储过程开荒_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}

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment