[英]Using SQL stored procedure to return row of table
我正在尝试在 SQL 中创建一个存储过程,它将返回该表的所有列的一行,并且该行将匹配snum
参数。 这是我正在使用的表。
我知道如何找到这样的单行:
select * from student where snum=578875478;
我想用存储过程做到这一点是这样做的:
delimiter $$
drop procedure if exists getStudentInfo;
create procedure getStudentInfo(IN sid INT, OUT info VARCHAR(4000))
begin
select * into info
from student
where student.snum=sid;
end $$
delimiter ;
我的想法是将snum
与sid
匹配并将整个内容返回到info
,但我收到一个错误消息
ERROR 1222 (21000): The used SELECT statements have a different number of columns
我必须从该表中返回一行,以便它可以与 JDBC 一起使用,结果可以是 output 到 Z6B7B655DD22FAA3F10677C512FAA3F10677C512493A8A0Z 中的控制台,但我不知道从这里做什么。 我已尝试解决此问题,但我不了解有关其工作原理的文档。
这也是我的 java 代码:
package MySQLDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.CallableStatement;
import java.sql.Types;
public class SimpleStoreProcedureDemo {
// info changed for privacy
static final String databasePrefix ="database";
static final String netID ="netID";
static final String hostName ="host";
static final String databaseURL ="jdbc:mariadb://"+hostName+"/"+databasePrefix;
static final String password="password";
private Connection connection = null;
private Statement statement = null;
private ResultSet resultSet = null;
public void Connection(){
try {
Class.forName("org.mariadb.jdbc.Driver");
System.out.println("databaseURL"+ databaseURL);
connection = DriverManager.getConnection(databaseURL, netID, password);
System.out.println("Successfully connected to the database");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
} // end of Connection
public void simpleStoreProcedure(String spName) {
try {
statement = connection.createStatement();
String result = "";
CallableStatement myCallStmt = connection.prepareCall("{call "+spName+"(?)}");
myCallStmt.registerOutParameter(1,Types.VARCHAR);
myCallStmt.execute();
result = myCallStmt.getString(1);
System.out.println(result);
}
catch (SQLException e) {
e.printStackTrace();
}
} // end of simpleQuery method
public static void main(String args[]) {
SimpleStoreProcedureDemo demoObj = new SimpleStoreProcedureDemo();
demoObj.Connection();
String spName ="getstudentInfo";
demoObj.simpleStoreProcedure(spName);
}
}
不需要输出参数等。 您可以直接从存储过程返回结果集,如下所示:
create procedure getStudentInfo(IN p_sid INT)
select * from student where snum = p_sid;
请注意,使用这种技术,您甚至不需要begin
/ end
块,也不需要修改默认分隔符。
替换 select 语句以返回string
而不是table
类型。由于您已编码以检索 jdbc 中的字符串 output, jdbc
调用信息变量应具有 char 数据类型。
col1,col2,col3 和 col4 是学生表的列,根据需要替换。 char(44)
是 output 中的逗号分隔符。
select col1+char(44)+col2+char(44)+col3+char(44)+col4
into info
from student
where student.snum=sid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.