以前用的是Statement 和PreparedStatement
调用存储过程就用到
CallableStatement cstmt =conn.prepareCall("call p(?,?,?,?)");
声明一个叫p的存储过程,需要4个参数其中1,2为输入参数
3输出参数,4为输入输出参数(在sqlserver里没有这样的参数)
是输出参数的我们在程序里要说明一下如:
表明这个是第3个问号上面的,切类型是int 型号的
isterOutParameter(4,Types.INTEGER)
输入输出参数也必须说明
cstmt.setInt(1,3);
cstmt.setInt(2,3);
cstmt.setInt(4,3); 把3个输入参数给值;
System.out.Int(3));
System.out.Int(4));
现在就可以用方法来取值了
最后cstmt.close要关闭
1 使用不带参数的存储过程
public static void executeStoredProcedure(Connection con) {
try {
CallableStatement cstmt = con.prepareCall("{call dbo.GetContactFormalNames}");
ResultSet rs = uteQuery();
while (rs.next()) {
System.out.String("FormalName"));
}
}
rs.close();
cstmt.close();
catch (Exception e) {
e.printStackTrace();
}
}
2 使用带有输入参数的存储过程
public static void executeStoredProcedure(Connection con) {
try {
CallableStatement cstmt = con.prepareCall("{call dbo.uspGetEmployeeManagers(?)}");
cstmt.setInt(1, 50);
ResultSet rs = uteQuery();
while (rs.next()) {
System.out.println("EMPLOYEE:");
System.out.String("LastName") + ", " + rs.getString("FirstName"));
System.out.println("MANAGER:");
System.out.String("ManagerLastName") + ", " + rs.getString("ManagerFirstName"));
System.out.println();
}
}
rs.close();
cstmt.close();
catch (Exception e) {
e.printStackTrace();
}
}
3 使用带有输出参数的存储过程
public static void executeStoredProcedure(Connection con) {
try {
CallableStatement cstmt = con.prepareCall("{call dbo.GetImmediateManager(?, ?)}");
cstmt.setInt(1, 5);
sql存储过程实例
System.out.println("MANAGER ID: " + Int(2));
}
catch (Exception e) {
e.printStackTrace();
}
}
4 使用带有返回状态的存储过程
作为示例,在SQL Server 2005 AdventureWorks 示例数据库中创建以下存储过程:
CREATE PROCEDURE CheckContactCity
@cityName CHAR(50)
AS
BEGIN
IF ((SELECT COUNT(*)
FROM Person.Address
WHERE City = @cityName) > 1)
RETURN 1
ELSE
RETURN 0
END
public static void executeStoredProcedure(Connection con) {
try {
CallableStatement cstmt = con.prepareCall("{? = call dbo.CheckContactCity(?)}");
cstmt.setString(2, "Atlanta");
System.out.println("RETURN STATUS: " + Int(1));
}
cstmt.close();
catch (Exception e) {
e.printStackTrace();
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。