一、對存儲過程的調用分三部分
1.連接(與數據庫建立連接)
- Class.forName("COM.ibm.db2.jdbc.Net.DB2Driver").newInstance();
- Connection con=DriverManager.getConnection(url,user,passWord);
2.注冊輸出參數
- cs.registerOutParameter (3, Types.INTEGER);
3.調用存儲過程:
- CallableStatement cs=con.prepareCall("{call store_name(參數,參數,參數)}");
二、調用舉例:
- import Java.Net.URL;
- import Java.sql.*;
- class test2
- {
- public static void main(String args[])
- {
- String url = "jdbc:db2://wellhope/sample";
- String user="db2admin";
- String passWord="db2admin";
- try
- {
- Class.forName("COM.ibm.db2.jdbc.Net.DB2Driver").newInstance();
- //與數據庫建立連接
- Connection con=DriverManager.getConnection(url,user,passWord);
- checkForWarning(con.getWarnings());
- DatabaseMetaData dma=con.getMetaData();
- String str="This is a string";
- //int hashcode=str.hashCode();
- //System.out.println("Hashcode "+hashcode);
- //創建Statement對象,用於執行SQL語句
- Statement stmt=con.createStatement();
- //創建CallableStatement對象,用於執行存儲過程
- CallableStatement cs=con.prepareCall("{call PRO_YHDL1(?,?,?)}");
- //注冊輸出參數
- cs.registerOutParameter (3, Types.INTEGER);
- int result = 0;
- cs.setString(1,"123");
- cs.setString(2,"123");
- cs.execute();
- result = cs.getInt (3);
- dispResultSet(result);
- cs.close();
- con.close();
- }
- catch(SQLException ex)
- {
- System.out.println(" * * * SQLException caught * * * ");
- while(ex!=null)
- {
- System.out.println("SQLState: "+ex.getSQLState());
- System.out.println("Message: "+ex.getMessage());
- System.out.println("Vendor: "+ex.getErrorCode());
- exex=ex.getNextException();
- System.out.println("");
- }
- }
- catch(Java.lang.Exception ex)
- {
- ex.printStackTrace();
- }
- }
三、存儲過程舉例:
Pro_yhdl1是一個存儲過程,它的功能是從數據庫表YHDL中取出PWD:
- import Java.sql.*;
- public class Pro_yhdl1
- {
- public static void pro_yhdl1 ( String m_id,
- String m_pwd,
- int[] result ) throws SQLException, Exception
- {
- // Get connection to the database
- Connection con = DriverManager.getConnection("jdbc:default:connection");
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql;
- String m_passWord="";
- sql = "SELECT"
- + " DB2ADMIN.YHDL.PWD"
- + " FROM"
- + " DB2ADMIN.YHDL"
- + " WHERE"
- + " ("
- + " ( "
- + " DB2ADMIN.YHDL.ID = '"+m_id.trim()+"'"
- + " )"
- + " )";
- stmt = con.prepareStatement( sql );
- rs = stmt.executeQuery();
- // Access query results
- while (rs.next())
- {
- m_passWord=rs.getString(1);
- m_passWordm_passWord=m_passWord.trim();
- if (rs.wasNull())
- System.out.print("NULL");
- else
- System.out.print(m_passWord);
- }
- if(m_passWord.equals(m_pwd.trim()))
- {
- result[0] =1;
- }
- else
- {
- result[0] =0;
- }
- // close open resources
- if (rs != null) rs.close();
- if (stmt != null) stmt.close();
- if (con != null) con.close();
- // set return parameter
- //result[0] = result[0];
- }
- }
關於DB2數據庫調用存儲過程的知識就介紹到這裡了,希望本次的介紹能夠對您有所幫助。