search
HomeDatabaseMysql TutorialmySql-数据库之存储过程学习总结_MySQL

mySql-数据库之存储过程学习总结_MySQL

May 27, 2016 pm 02:12 PM
mysqlstored procedure

bitsCN.com

之前在工作中总是听别人提到存储过程,觉得是个很高深的东西,利用工作之余,看了下相关的知识,现将学习知识总结如下,希望可以为刚学习的人提供些许帮助。

开发环境:Navicat For Mysql。

MySQL存储过程

1.1、CREATE  PROCEDURE  (创建)

CREATE PROCEDURE存储过程名 (参数列表)
   BEGIN
         SQL语句代码块
END
注意:
由括号包围的参数列必须总是存在。如果没有参数,也该使用一个空参数列()。每个参数默认都是一个IN参数。要指定为其它参数,可在参数名之前使用关键词 OUT或INOUT
实例演练:
eg1,带(输出参数)返回值的存储过程:
1、建表
create table abin5(
id int,
name5 VARCHAR(39)
)
2、创建存储过程
create procedure pabin5(out n int)
BEGIN
 select count(*) from abin5;
END
3、测试存储过程
call pabin5(@n)

eg2,带输入参数的存储过程:
1、建立存储过程
create procedure pabin6(in n int)
BEGIN
 SELECT * FROM abin5 where id=n;
END
2、测试存储过程
SET @n=1;
CALL pabin6(@n)
或者
CALL pabin6(1)
<br>
在mysql客户端定义存储过程的时候使用delimiter命令来把语句定界符从;变为//。
当使用delimiter命令时,你应该避免使用反斜杠(&lsquo;"&rsquo;)字符,因为那是MySQL的转义字符。
如:
mysql> delimiter //
mysql> CREATE PROCEDURE simpleproc (OUT param1 INT)
    -> BEGIN
    ->   SELECT COUNT(*) INTO param1 FROM t;
    -> END
    -> //
Query OK, 0 rows affected (0.00 sec)

1.2         ALTER  PROCEDURE (修改)

ALTER PROCEDURE 存储过程名SQL语句代码块
这个语句可以被用来改变一个存储程序的特征。

1.3         DROP  PROCEDURE (删除)

DROP PROCEDURE  IF  EXISTS存储过程名

eg:DROP PROCEDURE IF EXISTS proc_employee (proc_employee 存储过程名)

这个语句被用来移除一个存储程序。不能在一个存储过程中删除另一个存储过程,只能调用另一个存储过程

1.4         SHOW  CREATE  PROCEDURE(类似于SHOW CREATE TABLE,查看一个已存在的存储过程)

SHOW CREATE PROCEDURE 存储过程名

1.5         SHOW  PROCEDURE  STATUS (列出所有的存储过程)

SHOW  PROCEDURE  STATUS

1.6         CALL语句(存储过程的调用)

CALL 存储过程名(参数列表)

CALL语句调用一个先前用CREATE PROCEDURE创建的程序。
CALL语句可以用声明为OUT或的INOUT参数的参数给它的调用者传回值。
存储过程名称后面必须加括号,哪怕该存储过程没有参数传递

1.7         BEGIN ... END(复合语句)

[begin_label:]
BEGIN
    [statement_list]
END
[end_label]

存储子程序可以使用BEGIN ... END复合语句来包含多个语句。

statement_list 代表一个或多个语句的列表。statement_list之内每个语句都必须用分号(;)来结尾。

复合语句可以被标记。除非begin_label存在,否则end_label不能被给出,并且如果二者都存在,他们必须是同样的。

1.8         DECLARE语句(用来声明局部变量)

DECLARE语句被用来把不同项目局域到一个子程序:局部变量

DECLARE仅被用在BEGIN ... END复合语句里,并且必须在复合语句的开头,在任何其它语句之前。

1.9         存储程序中的变量

1.1             DECLARE局部变量

DECLARE var_name[,...] type [DEFAULT value]
这个语句被用来声明局部变量。
要给变量提供一个默认值,请包含一个DEFAULT子句。
值可以被指定为一个表达式,不需要为一个常数。
如果没有DEFAULT子句,初始值为NULL。
局部变量的作用范围在它被声明的BEGIN ... END块内。
它可以被用在嵌套的块中,除了那些用相同名字声明变量的块。

1.2             变量SET语句

SET var_name = expr [, var_name = expr]
在存储程序中的SET语句是一般SET语句的扩展版本。
被参考变量可能是子程序内声明的变量,或者是全局服务器变量。
在存储程序中的SET语句作为预先存在的SET语法的一部分来实现。这允许SET a=x, b=y, ...这样的扩展语法。
其中不同的变量类型(局域声明变量及全局和集体变量)可以被混合起来。
这也允许把局部变量和一些只对系统变量有意义的选项合并起来。

1.3             SELECT ... INTO语句

SELECT col_name[,...] INTO var_name[,...] table_expr
这个SELECT语法把选定的列直接存储到变量。
因此,只有单一的行可以被取回。
SELECT id,data INTO x,y FROM test.t1 LIMIT 1;
注意,用户变量名在MySQL 5.1中是对大小写不敏感的。

重要: SQL变量名不能和列名一样。如果SELECT ... INTO这样的SQL语句包含一个对列的参考,并包含一个与列相同名字的局部变量,MySQL当前把参考解释为一个变量的名字。

1.10     MySQL 存储过程参数类型(in、out、inout)

此小节内容来自:

参见地址:http://www.blogjava.net/nonels/archive/2009/04/22/233324.html

MySQL 存储过程参数(in

MySQL 存储过程 “in” 参数:跟 C 语言的函数参数的值传递类似, MySQL 存储过程内部可能会修改此参数,但对 in 类型参数的修改,对调用者(caller)来说是不可见的(not visible)。

MySQL 存储过程参数(out

MySQL 存储过程 “out” 参数:从存储过程内部传值给调用者。在存储过程内部,该参数初始值为 null,无论调用者是否给存储过程参数设置值

MySQL 存储过程参数(inout

MySQL 存储过程 inout 参数跟 out 类似,都可以从存储过程内部传值给调用者。不同的是:调用者还可以通过 inout 参数传递值给存储过程。

总结

如果仅仅想把数据传给 MySQL 存储过程,那就使用“in” 类型参数;如果仅仅从 MySQL 存储过程返回值,那就使用“out” 类型参数;如果需要把数据传给 MySQL 存储过程,还要经过一些计算后再传回给我们,此时,要使用“inout” 类型参数。

1.11     例子:

1.1            创建存储过程

带(输出参数)返回值的存储过程:

--删除存储过程

DROP PROCEDURE IF EXISTS proc_employee_getCount

--创建存储过程

CREATE PROCEDURE proc_employee_getCount(out n int)

BEGIN

     SELECT COUNT(*) FROM employee ;

END

--MYSQL调用存储过程

CALL proc_employee_getCount(@n);

带输入参数的存储过程:

--删除存储过程

DROP PROCEDURE IF EXISTS proc_employee_findById;

--创建存储过程

CREATE PROCEDURE proc_employee_findById(in n int)

BEGIN

     SELECT * FROM employee where id=n;

END

--定义变量

SET @n=1;

--调用存储过程

CALL proc_employee_findById(@n);

操作存储过程时应注意:

1.          删除存储过程时只需要指定存储过程名即可,不带括号;

2.          创建存储过程时,不管该存储过程有无参数,都需要带括号;

3.          在使用SET定义变量时应遵循SET的语法规则;

SET @变量名=初始值;

4.          在定义存储过程参数列表时,应注意参数名与数据库中字段名区别开来,否则将出现无法预期的结果

1.12     Java代码调用存储过程(JDBC)

相关APIjava.sql.CallableStatement

使用到java.sql.CallableStatement接口,该接口专门用来调用存储过程;

该对象的获得依赖于java.sql.Connection;

通过Connection实例的prepareCall()方法返回CallableStatement对象

prepareCall()内部为一固定写法{call 存储过程名(参数列表1,参数列表2)}可用?占位

eg: connection.prepareCall("{call proc_employee(?)}");

存储过程中参数处理:

输入参数:通过java.sql.CallableStatement实例的setXXX()方法赋值,用法等同于java.sql.PreparedStatement

输出参数:通过java.sql.CallableStatement实例的registerOutParameter(参数位置, 参数类型)方法赋值,其中参数类型主要使用java.sql.Types中定义的类型

Java代码调用带输入参数的存储过程 (根据输入ID查询雇员信息)

publicvoid executeProcedure()

    {

        try {

            /**

             *callableStatementjava.sql.CallableStatement

             *connectionjava.sql.Connection

             *jdbc调用存储过程原型

             *{call存储过程名(参数列表1,参数列表2)}可用?代替

             */

            callableStatement=connection.prepareCall("{call proc_employee_findById(?)}");

            callableStatement.setInt(1, 1); //设置输入参数

            resultSet=callableStatement.executeQuery();//执行存储过程

            if(resultSet.next())

            {

                System.out.println(resultSet.getInt(1)+""t"+resultSet.getString(2));

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }  

Java代码调用带输出参数的存储过程 (返回数据库中的记录数)

publicvoid executeProcedure()

    {

        try {

            /**

             *callableStatementjava.sql.CallableStatement

             *connectionjava.sql.Connection

             *jdbc调用存储过程原型

             *{call存储过程名(参数列表1,参数列表2)}可用?代替

             */

            callableStatement=connection.prepareCall("{call proc_employee_getCount(?)}");

            //设置输出参数

            callableStatement.registerOutParameter(1, Types.INTEGER);

            //执行存储过程

            resultSet=callableStatement.executeQuery();

            if(resultSet.next())

            {

                System.out.println(resultSet.getInt(1));

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

 

 

参考网址:http://www.blogjava.net/sxyx2008/archive/2009/11/24/303497.html

以上就是mySql-数据库之存储过程学习总结_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!

<br>

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 role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Describe the different SQL transaction isolation levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable) and their implications in MySQL/InnoDB.Apr 15, 2025 am 12:11 AM

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL vs. Other Databases: Comparing the OptionsMySQL vs. Other Databases: Comparing the OptionsApr 15, 2025 am 12:08 AM

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

How does MySQL index cardinality affect query performance?How does MySQL index cardinality affect query performance?Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

MySQL: Resources and Tutorials for New UsersMySQL: Resources and Tutorials for New UsersApr 14, 2025 am 12:16 AM

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

Real-World MySQL: Examples and Use CasesReal-World MySQL: Examples and Use CasesApr 14, 2025 am 12:15 AM

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.