JDBC 存儲過程IN參數(shù)

2018-03-21 14:19 更新

JDBC教程 - JDBC 存儲過程IN參數(shù)


以下示例顯示如何使用in參數(shù)調(diào)用存儲過程。

下面列出了用PL/SQL編寫的Oracle存儲過程。它向Person表插入一行。過程中的參數(shù)都標(biāo)記為IN作為輸入?yún)?shù)。

CREATE OR REPLACE PROCEDURE insertPERSON(
     p_userid IN PERSON.USER_ID%TYPE,
     p_username IN PERSON.USERNAME%TYPE,
     p_createdby IN PERSON.CREATED_BY%TYPE,
     p_date IN PERSON.CREATED_DATE%TYPE)
IS
BEGIN

  INSERT INTO PERSON ("USER_ID", "USERNAME", "CREATED_BY", "CREATED_DATE") 
  VALUES (p_userid, p_username,p_createdby, p_date);

  COMMIT;

END;
/

例子

以下代碼從 Connection 創(chuàng)建一個 CallableStatement 并傳遞存儲過程的名稱。

存儲過程的參數(shù)都標(biāo)有問號。

然后參數(shù)從 CallableStatement 設(shè)置為setXXX方法的值。

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;

public class Main {
  private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
  private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:YourDatabase";
  private static final String DB_USER = "user";
  private static final String DB_PASSWORD = "password";

  public static void main(String[] argv) throws Exception {
    Class.forName(DB_DRIVER);
    Connection dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
        DB_PASSWORD);

    CallableStatement callableStatement = null;
    String insertStoreProc = "{call insertPERSON(?,?,?,?)}";

    java.util.Date today = new java.util.Date();
    callableStatement = dbConnection.prepareCall(insertStoreProc);
    callableStatement.setInt(1, 1000);
    callableStatement.setString(2, "name");
    callableStatement.setString(3, "system");
    callableStatement.setDate(4, new java.sql.Date(today.getTime()));

    callableStatement.executeUpdate();
    System.out.println("Record is inserted into PERSON table!");
    callableStatement.close();
    dbConnection.close();
  }
}


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號