mysql 存储过程

存储过程介绍

       存储过程是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中。用户通过指定存储过程的名字并给出参数(如果该存储过程带有参数)来执行它。

        存储过程可由应用程序通过一个调用来执行,而且允许用户声明变量 。 同时,存储过程可以接收和输出参数、返回执行存储过程的状态值,也可以嵌套调用。

  优点:

           1、减少网络通信量。调用一个行数不多的存储过程与直接调用SQL语句的网络通信量可能不会有很大的差别,可是如果存储过程包含上百行SQL语句,那么其性能绝对比一条一条的调用SQL语句要高得多。

           2、执行速度更快。存储过程创建的时候,数据库已经对其进行了一次解析和优化。其次,存储过程一旦执行,在内存中就会保留一份这个存储过程,这样下次再执行同样的存储过程时,可以从内存中直接中读取。

           3、更强的安全性。存储过程是通过向用户授予权限(而不是基于表),它们可以提供对特定数据的访问,提高代码安全,比如防止 SQL注入。

  缺点:

          1、可移植性方面:当从一种数据库迁移到另外一种数据库时,不少的存储过程的编写要进行部分修改。

          2、存储过程需要花费一定的学习时间去学习

  一、创建存储过程 

   1、没有参数   

CREATE PROCEDURE helloWord ()
    LANGUAGE SQL  
    DETERMINISTIC
    SQL SECURITY DEFINER
    COMMENT 'A procedure'
    BEGIN
    SELECT 'Hello World !';
END
1) 首先在定义好终结符后,使用CREATE PROCEDURE+存储过程名的方法创建存储过程,LANGUAGE选项指定了使用的语言,这里默认是使用SQL。
  2) DETERMINISTIC关键词的作用是,当确定每次的存储过程的输入和输出都是相同的内容时,可以使用该关键词,否则默认为NOT DETERMINISTIC。
  3) SQL SECURITY关键词,是表示调用时检查用户的权限。当值为INVOKER时,表示是用户调用该存储过程时检查,默认为DEFINER,即创建存储过程时检查。
  4) COMMENT部分是存储过程的注释说明部分。
  5) 在BEGIN END部分中,是存储过程的主体部分。

//删除存储过程
DROP PROCEDURE IF EXISTS helloWord;
//调用存储过程----->也可以传递参数
CALL helloWord()
View Code

   2、带参数

//带参数的存储过程
CREATE PROCEDURE selectUser(IN userCode VARCHAR(255))
    BEGIN
        select * from tuser where user_code=userCode;
    END
CALL selectUser('9001');

create procedure usp_GetEmployeeName(IN userCode VARCHAR(255), OUT name VARCHAR(255))
 begin
        select regName into name from tuser where user_code=userCode;
 end
CALL usp_GetEmployeeName('9001',@uName);

create procedure pr_param_inout(inout id int)
    begin
    select id as id_inner_1;  -- id 值为调用者传进来的值
    if (id is not null) then
    set id = id + 1;
    select id as id_inner_2;
    else
    select 1 into id;
    end if;
    select id as id_inner_3;
    end;

set @id = 10;
call pr_param_inout(@id);
View Code

 二、java (jdbc)调用存储过程

package com.jalja.mysql;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

public class StoredProcedure {
    private static String url = "jdbc:mysql://192.168.0.200:3307/study";
    private static String user = "root";
    private static String password = "jalja";
    private StoredProcedure() {
    }
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    public static Connection getConnection()  {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void free(Connection conn) {
        if (conn != null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    /* 调用存储过程
     * 创建存储过程
         CREATE procedure stu_proc(IN v_id INT, OUT v_name VARCHAR(20))
        BEGIN 
          SELECT name INTO v_name FROM student where id = v_id;
        END;
     */
    private static void test01() throws Exception {
        Connection conn = null;
        CallableStatement statement = null;
        String sql = "call stu_proc(?, ?)";
        try {
            conn = getConnection();
            statement = conn.prepareCall(sql);
            statement.setInt(1, 1001);
            statement.registerOutParameter(2, Types.VARCHAR);
            statement.executeUpdate();
            String sname = statement.getString(2);
            System.out.println(sname);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
          free(conn);
        }
    }
    public static void main(String[] args) throws Exception {
        test01();
    }
}
View Code

        

原文地址:https://www.cnblogs.com/jalja/p/4632510.html