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

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

Jun 07, 2016 pm 04:24 PM
java m mysql getting Started storage Example transfer process

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
Copy after login

??? 下面开始介绍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
Copy after login

?? (二)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;
Copy after login

??? Repeat测试:

???

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

??? (三)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;
Copy after login

??? loop 测试:

???

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

??? 上面介绍的是一个简单的带输入输出的存储过程,下面在介绍一个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;
Copy after login

??? in out参数测试:

??? Navicat查询界面测试:

???

call proc_mysql_inout_test(2,@out);
select @out
Copy after login

??? 返回值很奇怪结果是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;
Copy after login

??

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

??

drop procedure proc_mysql_getsum_bywhile
Copy after login

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

??

select name from mysql.proc where db='test'
Copy after login

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

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

??

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

??? 测试方法为:

???

call proc_mysql_return_cursor_method();
Copy after login

??? 下面我简单介绍下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;
	}
Copy after login

?? 我就以我写的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);
	}
Copy after login

?? 输入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);
	}
Copy after login

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

???

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));
		}
	}
Copy after login

??? 很简单吧。

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

???? 全文完。

??

???

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles