本系列首篇介紹最基礎的存儲過程調用:只有輸入參數、無輸出參數、無結果集返回的場景。雖簡單,但奠定了 CallableStatement 使用的基礎模式。
create procedure getsum
@n int = 0
as
declare @sum int, @i int
set @sum = 0; set @i = 0
while @i <= @n begin
set @sum = @sum + @i
set @i = @i + 1
end
print 'the sum is ' + ltrim(rtrim(str(@sum)))
SQL 測試:exec getsum 100(控制台輸出結果,但無返回值供 Java 獲取)。
import java.sql.*;
public class ProcedureTest {
public static void main(String args[]) throws Exception {
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
Connection conn = DriverManager.getConnection("jdbc:odbc:mydata", "sa", "");
CallableStatement c = conn.prepareCall("{call getsum(?)}");
c.setInt(1, 100); // 設置輸入參數
c.execute(); // 執行
conn.close();
}
}
{call 過程名(?,...)}。setXxx(index, value) 設置,索引從 1 開始。execute() 觸發執行。print 輸出無法直接被 Java 捕獲(需重定向或改為輸出參數/結果集)。後續文章將遞進講解:
建議按序學習,逐步掌握 JDBC 與存儲過程交互的完整技能棧。