您的位置:首页 > 编程语言 > Java开发

java和mysql存储过程

2016-04-03 00:00 489 查看
我们常用的操作数据库语言SQL语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的SQL语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它。

一个存储过程是一个可编程的函数,它在数据库中创建并保存。它可以有SQL语句和一些特殊的控制结构组成。当希望在不同的应用程序或平台上执行相同的函数,或者封装特定功能时,存储过程是非常有用的。数据库中的存储过程可以看做是对编程中面向对象方法的模拟。它允许控制数据的访问方式。

下面是一个存储过程的实例,包括证明创建和怎么去调用,都是在项目里面拷的并且简化了一点:

首先有一张表:

CREATE TABLE `NEWS`(
`id` int(11) not null AUTO_INCREMENT,
`title` varchar(100) not null default '无标题',
`publishTime` datetime not null,
`content` TEXT not null,
`viewCount` int(11) not null default 0,
`city` varchar(30) not null default '为分类',
`category` smallint not null default '1',
`description` varchar(255),
`editor` varchar(50) not null,
`editorId` int(11) not null,
`examined` smallint not null default 0,
primary key(`id`)
);


然后创建一个存储过程:

DELIMITER //

CREATE PROCEDURE proc(in newId int)

BEGIN
declare c int;
set c=(select viewCount from NEWS where id=newId);
update NEWS set viewCount = c + 1 where id=newId;
SELECT * FROM NEWS where id = newId;

END

//

DELIMITER ;

上面存储过程的作用是每次查询一条记录时都向浏览次数中加1;

DELIMITER // 是把分隔符改为//,避免在函数体中的;被mysql认为是分隔符,begin和end之间编写存储过程的函数体。

结束后DELLIMITER;把分隔符重新恢复为;

在函数体中的变量定义:

declare 变量名 变量数据类型 eg. declare c int;

变量赋值:

set 变量名 =

在终端先试试存储过程:

set @newId = 1; #设置一个变量

call proc(@newsId);#调用刚才创建的存储过程。

在 java 代码里调用:

Connection connection = null;
CallableStatement call = null;
ResultSet set = null;
try {

connection = C3P0Util.getConnection();
call = connection.prepareCall("{call proc(?)}");//call存储过程的名称
call.setInt(1, 176);
set = call.executeQuery();
while(set.next()){

System.out.println(set.getInt("id"));//结果
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally{

try {

connection.close();
call.close();
set.close();

} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}


开始,我的控制台下面报错:

Callable statments not supported.

就是不支持存储过程,我把mysql-connector换成5.0以上版本就好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql