本文實例講述了java編程調用存儲過程中得到新增記錄id號的實現方法。分享給大家供大家參考,具體如下:
關于ms sql server2000的存儲過程,主要作用是在表test中插入一條記錄,然后得到新增加記錄的id號。
test表三個字段:
ID:自動增長
yhm:用戶名 字符串類型
kl: 密碼 字符串類型
那么在java程序中如何調用這個存儲過程才能實現,得到新增加記錄的id號
存儲過程如下:
1
2
3
4
5
6
7
8
9
10
|
CREATE PROCEDURE yh_insert @yhm varchar (50),@kl varchar (50) AS begin set nocount on insert into test(yhm,kl) values (@yhm,@kl) set nocount off select newid=@@identity end GO |
解決辦法:
在查詢分析器中執行sp的方法
1
2
3
|
declare @id int exec sp_yh_insert 'tetstst' , '111111' ,@id output select @id |
修改sp如下:使用輸出參數來存儲得到的新的Id
1
2
3
4
5
6
7
8
9
10
11
|
CREATE PROCEDURE sp_yh_insert @yhm varchar (50),@kl varchar (50),@id int output AS begin set nocount on insert into test(yhm,kl) values (@yhm,@kl) set nocount off --select newid=@@identity select @id=@@identity --關鍵 end GO |
java程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
public String call_sp_insert_jh(String yhm,String kl) throws Exception { String strFlag = "" ; String strString = "" ; Connection conn = null ; try { conn = db.getConnection(); //CallableStatement proc = conn.prepareCall(strSql); CallableStatement proc=conn.prepareCall( "{call sp_yh_insert(?,?,?)}" ); proc.setString( 1 , "往往外餓餓餓額" ); //給第一個輸入參數賦值 proc.setString( 2 , "1111111" ); //給第2個輸入參數賦值 proc.registerOutParameter( 3 ,Types.INTEGER); //處理輸出參數 proc.execute(); //執行sp int id = proc.getInt( 3 ); //得到返回值的值 strString=Integer.toString(id); strFlag=strString ; } catch (SQLException e) { System.out.println( "proc execute error" +strString); } finally { //關閉數據庫聯接 try { conn.close(); } catch (Exception sqle) { //產生新 異常,則拋出新 程序異常 //throw new Exception("[DBBean.executeQuery(sql,tname)]","10"); System.out.println( "出錯了" ); } } return strFlag; } |
希望本文所述對大家Java程序設計有所幫助。