How do I pass an array of timestamps to the Postgres function using Java and JDBC?
Here's the signature of the function:
CREATE OR REPLACE FUNCTION getlistcount(_id integer, _subs text, _download_array timestamp without time zone[], _filter integer, _fault text) RETURNS refcursor AS...
Here is the Java code that creates the array:
GregorianCalendar[] dataDownloads =
downloadTimes.toArray(new GregorianCalendar[downloadTimes.size()]);
Array sqlArray = conn.createArrayOf("timestamp", dataDownloads);
cstmt.setArray(4, sqlArray);
The downloadTimes are List passed into the Java function.
One hint: we need to concatenate the time with the date, according to the Postgres documentation .
I found an answer on StackOverflow that is similar , but uses the PreparedStatement rather than the JDBC notation.
//Get timezone from first entry, assuming all same timezone
if(!downloadTimes.isEmpty()) {
cal.setTimeZone(downloadTimes.get(0).getTimeZone());
}
//Create an array of timestamps
java.sql.Timestamp [] array = new java.sql.Timestamp [downloadTimes.size()];
for(int i=0; i < array.length; i++) {
array[i] = new java.sql.Timestamp(downloadTimes.get(i).getTimeInMillis());
}
//pass the array to JDBC call
//conn is the connection, and cstmt is the CallableStatement
Array sqlArray = conn.createArrayOf("timestamp", array);
cstmt.setArray(4, sqlArray);
The array doesn't have to be of the old java.sql.Timestamp class, you can use java.time classes instead.
Like this
LocalDateTime[] localTimes = new LocalDateTime[]{LocalDateTime.now()};
Array sqlArray = conn.createArrayOf("timestamp", localTimes);
cstmt.setArray(4, sqlArray);
For timestamp with zone use java.time.OffsetDateTime
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.