我在将整数数组插入 Postgresql 表时遇到问题,我该怎么做?
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);
其中 ballNumbers 和 ballNumbersMegaBall 是 ArrayList。填入 2 位数字。
这是 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)
)
这是来自 Springboot 的错误:
There was an unexpected error (type=Internal Server Error, status=500). PreparedStatementCallback; bad SQL grammar [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. Use setObject() with an >explicit Types value to specify the type to use.
最佳答案
最近我遇到了类似的问题。我的解决方案:
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;
}
关于java - 如何在 Java Springboot 中使用 jdbcTemplate 将整数数组插入到 postgresql 表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41303587/