標籤:.sql statement sel strong param 列表 handle 參數 例子
這是我學習mysql預存程序時關心的幾個點內容,希望能對你們學習預存程序有所協助。
文法:
create procedure sp_name ([proc_parameter[,...]])
[characteristic ...]
begin
.......
end
Proc_parameter:預存程序的參數列表,多個參數彼此間用逗號分隔
格式[IN|OUT|INOUT] param_name type
IN(輸入參數)、OUT(輸出參數)、INOUT(輸出參數和輸入);
Param_name為參數名;
type為參數的資料類型。
Characteristic:用於描述儲存特徵
預存程序使用邏輯文法:
邏輯判斷:
1、if判斷
IF expression THEN commands
[ELSEIF expression THEN commands]
[ELSE commands]
END IF;
2、case判斷
CASE case_expression
WHEN when_expression THEN commands
WHEN when_expression THEN commands
ELSE commands
END CASE;
迴圈判斷:
1、WHILE……DO……END WHILE
2、REPEAT……UNTIL END REPEAT
3、LOOP……END LOOP
4、GOTO
Java對預存程序操作
1、擷取預存程序輸出值
--預存程序SQL
create procedure tb_pro(out op int)begin set op = 10end
java操作:
CallableStatement cs = con.prepareCall(sql);cs.registerOutParameter(1, java.sql.Types.INTEGER);//註冊預存程序的out型參數類型;使用之前必須註冊;cs.execute();System.out.println(cs.getInt(2)); //擷取out的輸出結果
2、擷取查詢結果集(來自select查詢),且有多個結果集如何處理?
-- 預存程序SQL
create procedure bach_pro()beginselect * from table1;select * from table2;end
java操作:
CallableStatement cs = con.prepareCall(sql); cs.execute(); ResultSet resultSet = cs.getResultSet(); //遍曆第一個結果集 while(resultSet.next()){ System.out.println(resultSet.getInt(1)); // 輸出結果集 } //擷取下一個結果集 ResultSet rs2; while(cs.getMoreResults()){ rs2 = cs.getResultSet(); while (rs2.next()) { System.out.println(rs2.getInt(1)); //輸出結果集列 } }
3、當我們要在預存程序中處理查詢結果集時,我們就需要使用到cursor,下面是cursor一個簡單的使用例子
begindeclare stop int default 0 ;--需要在cursor前聲明參數declare id_temp int; declare cur1 cursor for (select id from xinguan);declare continue handler for not found set stop = 1; --聲明cursor掃描完後設定值,用於結束迴圈open cur1;cur1_loop:loop fetch cur1 into id_temp; --從cursor中取值賦給變數 if stop then leave cur1_loop; end if;end loop cur1_loop;close cur1;end
Mysql預存程序(Java)