如何使用JDBCTemplate

时间:2017-07-10 10:10:13

标签: java postgresql jdbc jdbctemplate

我有一个存储函数,它接受数据库中的参数。

创建或替换功能

public.abc(
  id integer,
  title text,
  description text,
  valid_until_date timestamp with time zone,
  user_is_ext boolean,
  remarks text)
{
    //statements
}

我需要调用这个存储的函数。我可以使用以下查询直接在数据库中调用:

select  "abc" (0,'title','description','2010-01-01 00:00:00+01',false,'text')

但是我无法在SpringBoot应用程序中使用JDBC模板调用。

String sql="select  \"abc\" (?,?,?,?,?,?)";
List<Integer> ids=jdbcTemplate.query(sql,new Object[]{id,myObj.getTitle(),  myObj.getDescription(),  myObj.getValidDate(),  myObj.isUserExt(),  ,myObj.getRemarks()},new BeanPropertyRowMapper(Integer.class));

有人可以帮我弄清楚我错过了什么吗?

我得到&#34;列索引超出范围:&#34;错误。 我尝试使用&#34;更新&#34;而不是&#34;查询&#34; int ind=jdbcTemplate.update(sql, id,myObj.getTitle(), myObj.getDescription(), myObj.getValidUntilDate(), myObj.isUserExt(), myObj.getRemarks());

然后我得到以下错误

""2017-07-10 14:51:16 [http-bio-8080-exec-60] ERROR c.s.k.l.exceptions.ExceptionHandlers --- A result was returned when none was expected. –

尝试使用评论中提到的SimpleJDBC调用。在SQLParameter对象

中传递timestamp作为参数时获得低于错误

""2017-07-10 16:18:16 [http-bio-8080-exec-97] ERROR c.s.k.l.exceptions.ExceptionHandlers --- Bad value for type timestamp : org.springframework.jdbc.core.SqlParameter@3a4cbd06

1 个答案:

答案 0 :(得分:0)

最后我解决了!!

在我的情况下,我试图调用一个返回整数值的存储函数。请找到下面的代码段。

String sql="select * from \"stored_function_name\" (?,?,?,?,?,?,?,?,?)";
Integer result=jdbcTemplate.queryForObject(sql,Integer.class, new Object[] {all input parameters separated by coma});

同样,我们可以使用query的其他变体。

请确保传递给function的参数应该与postgres数据库中的数据类型相同。如果它是db中的时间戳并且您将日期作为字符串,则可以使用下面的代码将其转换为时间戳

Timestamp.valueOf("date_string in yyyy-mm-dd hh:mm:ss format")

谢谢大家!!