java 存储过程可以返回结果集吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10294687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can stored procedures return a result set?
提问by Dil Se...
I have a table named employee, which has his id, name, phone number. I am using MySQL as my database. I am using Java Swing for that. I am searching the employee table with name now using Java (I have used like
clause in my Java page).
我有一个名为employee 的表,里面有他的id、姓名、电话号码。我使用 MySQL 作为我的数据库。为此,我正在使用 Java Swing。我现在正在使用 Java 搜索带有名称的员工表(我like
在我的 Java 页面中使用了子句)。
Now I need to implement that function in stored procedures. Is it possible? And how can we take that resultset in Java code, if it is possible??
现在我需要在存储过程中实现该功能。是否可以?如果可能的话,我们如何在 Java 代码中获取该结果集?
Now I have written my stored procedure as follows
现在我写了我的存储过程如下
BEGIN
SELECT * FROM employee where empName like '%su%'
END
Sample code will be appreciated.. Thanks
示例代码将不胜感激..谢谢
回答by Mike Q
When executing a stored procedure it may actually return multiple ResultSet objects and/or update counts if it does several statements.
当执行一个存储过程时,它实际上可能返回多个 ResultSet 对象和/或更新计数,如果它执行多个语句。
You use CallableStatement
to execute the proc and then getResultSet()
or getUpdateCount()
to get the right result. For multiple results sets/statements you call getMoreResults()
to move through the results of the stored proc.
你CallableStatement
用来执行 proc 然后getResultSet()
orgetUpdateCount()
得到正确的结果。对于多个结果集/语句,您调用getMoreResults()
以在存储过程的结果中移动。
For a simple case like this you should just need to call getResultSet()
once and process it.
对于像这样的简单案例,您只需要调用getResultSet()
一次并处理它。
回答by Vinesh
First thing is you should write msql procedure that sends parameter for LIKE
,
第一件事是你应该编写发送参数的 msql 过程LIKE
,
CREATE PROCEDURE simpleproc (param1 CHAR(20))
BEGIN
SELECT * FROM employee where empName like param1;
END
Then from java program you can use this code to use procedure,
然后从java程序你可以使用这段代码来使用过程,
CallableStatement cstmt = con.prepareCall("{call simpleproc(?)}");
cstmt.setString(1, "%su%");
ResultSet rs = cstmt.executeQuery();
回答by Quassnoi
Yes you can. A stored procedure can even return multiple resultsets.
是的你可以。一个存储过程甚至可以返回多个结果集。
DELIMITER $$ -- recognized by mysql client but not phpmyadmin
CREATE PROCEDURE prc_test()
BEGIN
SELECT *
FROM employee
WHERE empName LIKE '%su%';
END;
$$
DELIMITER ;
CALL prc_test(); -- to call