將數組傳遞給數據庫函數有很多方法。一個簡單的一個情況如下:
首先,你應該建立在你的DB模式的TABLE
類型:
CREATE TYPE DATE_ARRAY AS TABLE OF DATE;
這之後你應該寫一FUNCTION
這個新類型的輸入:
-- a dummy function just for presenting the usage of input array
CREATE FUNCTION Date_Array_Test_Function(p_data IN DATE_ARRAY)
RETURN INTEGER
IS
TYPE Cur IS REF CURSOR;
MyCur cur;
single_date DATE;
BEGIN
/* Inside this function you can do anything you wish
with the input parameter: p_data */
OPEN MyCur FOR SELECT * FROM table(p_data);
LOOP
FETCH MyCur INTO single_date;
EXIT WHEN MyCur%NOTFOUND;
dbms_output.put_line(to_char(single_date));
END LOOP;
RETURN 0;
END Date_Array_Test_Function;
現在在java
代碼中,您可以使用以下代碼來調用具有數組輸入類型的此類函數:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
public class Main
{
public static void main(String[] args) throws SQLException
{
Connection c = DriverManager.getConnection(url, user, pass);
String query = "begin ? := date_array_test_function(?); end;";
// note the uppercase "DATE_ARRAY"
ArrayDescriptor arrDescriptor = ArrayDescriptor.createDescriptor("DATE_ARRAY", c);
// Test dates
Date[] inputs = new Date[] {new Date(System.currentTimeMillis()),
new Date(System.currentTimeMillis()),
new Date(System.currentTimeMillis())};
ARRAY array = new ARRAY(arrDescriptor, c, inputs);
CallableStatement cs = c.prepareCall(query);
cs.registerOutParameter(1, Types.INTEGER); // the return value
cs.setObject(2, array); // the input of the function
cs.executeUpdate();
System.out.println(cs.getInt(1));
}
}
希望這會有所幫助。
好運
那麼,這是什麼問題? – Nitish
我如何將一個日期列表傳遞給一個DB函數作爲其輸入參數?我如何比較開始日期是否落入函數內的這個日期? – Ann
看看[這個問題](http://stackoverflow.com/questions/19888520/pass-array-from-java-to-oracle-java-sql-sqlexception-fail-to-convert-to-intern)對於你的問題的第一部分。問題的第二部分是算法發展,它超出了SO問題的範圍。 – Nitish