search
HomeDatabaseMysql TutorialMysql容易存储过程入门示例与Java调用

Mysql容易存储过程入门示例与Java调用

Jun 07, 2016 pm 04:24 PM
javammysqlgetting StartedstorageExampletransferprocess

Mysql简单存储过程入门示例与Java调用 ??? ?昨天看了一篇介绍Mysql存储过程博客,链接如下: ???? http://my.oschina.net/u/1264926/blog/199831 ???? 我试着运行了下,一直报错,找了很久才发现Mysql存储过程赋值要用SET 变量名 = 表达式值,很久没有Mysql存

Mysql简单存储过程入门示例与Java调用

??? ?昨天看了一篇介绍Mysql存储过程博客,链接如下:

???? http://my.oschina.net/u/1264926/blog/199831

???? 我试着运行了下,一直报错,找了很久才发现Mysql存储过程赋值要用SET 变量名 = 表达式值,很久没有Mysql存储过程,好多东西都忘光了,而是写了本篇博文备忘,我使用的数据库版本是Mysql 5.6.14,使用了Navicat Premium图形界面,首先是我参考的链接:

????

http://www.cnblogs.com/jevo/p/3271359.html
http://phpzf.blog.51cto.com/3011675/793775

??? 下面开始介绍Mysql存储过程,语法之类的我就不写了,请自行谷歌,我的存储过程是完成1到limit之间的累加和,所以要用到循环,Mysql存储过程常用的循环语句有:While,Loop,Repeat,下面一一介绍怎么写:

??? (一)首先是使用While循环(WHILE……DO……END WHILE)

???

create procedure proc_mysql_getsum_bywhile(in v_limit int,out sum int)
begin
   declare i int default 0;
   set sum=0;
   while i<v_limit do begin set sum="sum+i;" i="i+1;" end while>
<p>??? <span>这里啰嗦一句,Mysql里面没有类似Oracle的DBMS_OUT.PUT_LINE之类的打印语句,想打印结果,请用select 变量。</span></p>
<p><span>?? While循环测试:</span></p>
<p>???</p>
<pre name="code" class="java">set @limit=100;
set @out=0;
call proc_mysql_getsum_bywhile(@limit,@out);
select @out

?? (二)repeat 循环(REPEAT……END REPEAT)

??

create procedure proc_mysql_getsum_byrepeat(in v_limit int,out sum int)
begin
   declare i int default 0;
   set sum=0;
   repeat 
      begin
      set sum=sum+i;
      set i=i+1;
       end;
      until i>v_limit
   end repeat;
   /**select sum;**/
end;

??? Repeat测试:

???

set @limit=100;
set @out=0;
call proc_mysql_getsum_byrepeat(@limit,@out);
select @out

??? (三)loop循环

???

create procedure proc_mysql_getsum_byloop(in v_limit int,out sum int)
begin
   declare i int default 0;
   set sum=0;
   loop_label:loop  
      begin
        set sum=sum+i;
        set i=i+1;
      if i>v_limit then 
            leave loop_label; 
       end if; 
       end;
   end loop;
   /**select sum;**/
end;

??? loop 测试:

???

set @limit=100;
set @out=0;
call proc_mysql_getsum_byloop(@limit,@out);
select @out

??? 上面介绍的是一个简单的带输入输出的存储过程,下面在介绍一个getUserById的存储过程,和上面的差不多。

??

create procedure proc_mysql_inout_test(in v_id int,out username varchar(20))
begin
   select username into username from user_t2 where id = v_id; 
   /**select username;**/
end;

??? in out参数测试:

??? Navicat查询界面测试:

???

call proc_mysql_inout_test(2,@out);
select @out

??? 返回值很奇怪结果是Blob。

??

??? Navicat命令行下测试:返回的是gbk编码的字符串,而直接select * from user_t2;无乱码,如下所示:

???

??? cmd 命令行下测试 无乱码,如下所示:

???

??? 如果想在存储过程中执行sql语句该怎么写呢?请看示例:

????测试新建表并填充值:

???

drop PROCEDURE proc_mysql_createtb_insert_data;
CREATE PROCEDURE proc_mysql_createtb_insert_data(IN loop_times INT) 
BEGIN  
DECLARE var INT DEFAULT 0;  
PREPARE MSQL FROM 'CREATE TABLE IF NOT EXISTS mysql_employee (id INT (10)  NOT NULL AUTO_INCREMENT,empname VARCHAR (16) NOT NULL COMMENT ''名字'',hiredate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,PRIMARY KEY (id)) ENGINE = INNODB DEFAULT CHARSET = utf8';
EXECUTE MSQL;  
deallocate prepare MSQL; 
WHILE var<loop_times do set var="var+1;" insert into mysql_employee values substr from dual end while>
<p>??? <span>测试</span><br>???</p>
<pre name="code" class="sql">call proc_mysql_createtb_insert_data(10);
select * from mysql_employee;

??

?? Mysql存储过程想要修改时只能先删除在新建,删除方法为:

??

drop procedure proc_mysql_getsum_bywhile

?? 查看某个数据库下面的存储过程方法为:

??

select name from mysql.proc where db='test'

?? 如果想和Oracle存储过程一样返回游标,怎么写呢,很遗憾,我所知道的是Mysql不支持Out ref_cur cursor之类的写法的,你可以在存储过程中新建临时表,结束时候删除临时表,方法请参考上面的新建表示例。

?? 另一种方法是直接select 内容,不写返回结果,如下所示:

??

CREATE PROCEDURE proc_mysql_return_cursor_method() 
begin
select * from user_t2;
end;

??? 测试方法为:

???

call proc_mysql_return_cursor_method();

??? 下面我简单介绍下Java中怎么调用Mysql存储过程,如果不感兴趣可以不用往下看了。

??? 首先是公共方法:

???

public Connection getMysqlConnection() {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";// 要操作的数据库名称
		String username = "root";// 数据库用户名
		String password = "123";// 密码
		return getConnection(driver, url, username, password);
	}

	public Connection getConnection(String driver, String url, String userName,
			String passwd) {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, userName, passwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

?? 我就以我写的while循环为例,输入int参数,输出int参数:

??

public void testMysqlProcedureRtnInt(Connection con, CallableStatement cs,
			int limit) throws Exception {
		cs = con.prepareCall("{call proc_mysql_getsum_bywhile(?,?)}");
		// 设置参数
		cs.setInt(1, limit);
		// 注册输出参数
		cs.registerOutParameter(2, oracle.jdbc.OracleTypes.INTEGER);
		// 执行过程
		cs.execute();
		// 获取结果
		int result = cs.getInt(2);
		System.out.println("结果为:" + result);
	}

?? 输入int,输出varchar类型方法类似:

??

public void testMysqlProcedureRtnVarchar(Connection con,
			CallableStatement cs, int id) throws Exception {
		cs = con.prepareCall("{call proc_mysql_inout_test(?,?)}");
		// 设置参数
		cs.setInt(1, id);
		// 注册输出参数
		cs.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);
		// 执行过程
		cs.execute();
		// 获取结果
		String result = cs.getString(2);
		System.out.println("结果为:" + result);
	}

??? 来看下返回类似游标类型的调用:

???

public void testMysqlProcedureRtnCursor(Connection con,
			CallableStatement cs, ResultSet rs) throws Exception {
		cs = con.prepareCall("{call proc_mysql_return_cursor_method()}");
		// 执行过程
		rs = cs.executeQuery();
		System.out.println("id" + "\t" + "username" + "\t" + "passwd");
		while (rs.next()) {
			System.out.println(rs.getInt(1) + "\t" + rs.getString(2) + "\t"
					+ rs.getString(3));
		}
	}

??? 很简单吧。

??? 上面的介绍到目前为知该结束了,本文系原创,转载请注明出处,谢谢。

???? 全文完。

??

???

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool