[英]How to insert Integer array into postgresql table using jdbcTemplate in Java Springboot?
I have problems with inserting Integer array into Postgresql Table, how do I go about this? 我在将Integer数组插入Postgresql Table时遇到问题,该如何解决?
String sql = "INSERT INTO draw_result (id, ball_numbers, balls_with_mega_ball, draw_dates, mega_plier) VALUES(?, ?, ?, ?, ?)";
Object[] params = {randomNumbers, ballNumbers, ballNumbersMegaBall, drawDates, megaPlier};
jdbcTemplate.update(sql, params);
Where ballNumbers and ballNumbersMegaBall are ArrayList. 其中ballNumbers和ballNumbersMegaBall是ArrayList。 Filled with 2 digit numbers.
填充2位数字。
Here is the PostgreSQL table: 这是PostgreSQL表:
CREATE TABLE public.draw_result
(
id bigint NOT NULL,
draw_dates date,
ball_numbers bigint[],
balls_with_mega_ball bigint[],
mega_plier bigint,
CONSTRAINT draw_result_pkey PRIMARY KEY (id)
)
And here is the Error from Springboot : 这是Springboot的错误:
There was an unexpected error (type=Internal Server Error, status=500).
发生意外错误(类型=内部服务器错误,状态= 500)。 PreparedStatementCallback;
PreparedStatementCallback; bad SQL grammar [INSERT INTO draw_result (id, >ball_numbers, balls_with_mega_ball, draw_dates, mega_plier) VALUES(?, ?, ?, ?, >?)];
错误的SQL语法[INSERT INTO draw_result(id,> ball_numbers,balls_with_mega_ball,draw_dates,mega_plier)VALUES(?,?,?,?,>?)]; nested exception is org.postgresql.util.PSQLException: Can't infer the SQL >type to use for an instance of java.util.ArrayList.
嵌套异常是org.postgresql.util.PSQLException:无法推断用于java.util.ArrayList实例的SQL类型。 Use setObject() with an >explicit Types value to specify the type to use.
将setObject()与> explicit Types值一起使用以指定要使用的类型。
Recently I had a similar problem. 最近我有一个类似的问题。 My solution:
我的解决方案:
public void setDrawResult(BigInteger id, List<BigInteger> ballNumbers, List<BigInteger> ballsWithMegaBall, Date drawDates,BigInteger megaPlier){
String sql = "INSERT INTO draw_result (id, ball_numbers, balls_with_mega_ball, draw_dates, mega_plier) VALUES(?, ?, ?, ?, ?)";
jdbcTemplate.update(sql
, id
, createSqlArray(ballNumbers)
, createSqlArray(ballsWithMegaBall)
, drawDates
, megaPlier
);
}
private java.sql.Array createSqlArray(List<BigInteger> list){
java.sql.Array intArray = null;
try {
intArray = jdbcTemplate.getDataSource().getConnection().createArrayOf("bigint", list.toArray());
} catch (SQLException ignore) {
}
return intArray;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.