JDBCTemplate查找行是否存在

问题描述 投票:3回答:2

我很好奇我应该如何使用spring jdbctemplate类来确定我的一个表中是否已存在记录或行?我试过了

int count = jdbcTemplate.queryForObject("select * from MyTable
                                  where Param = ?", new Object[] {myParam},
                                  Integer.class);
if(count ==0)
    //record does not exist

问题是虽然我不断得到EmptyResultAccessDataException的,当它不存在所以我更新了代码

try{
    jdbcTemplate.queryForObject("select * from MyTable
                                  where Param = ?", new Object[] {myParam},
                                  Integer.class);
} catch(EmptyResultAccessDataException e) {//insert the record}

如果记录确实存在,那么它会给我带来问题。所以我想我真正的问题是在表格中搜索记录存在的最佳方法是什么,因为我想添加所述记录,如果它没有,如果它没有做任何事情。

spring jdbc jdbctemplate
2个回答
7
投票

你可以使用这样的东西:

String sql = "SELECT count(*) FROM MyTable WHERE Param = ?";
boolean exists = false;
int count = getJdbcTemplate().queryForObject(sql, new Object[] { "paramValue" }, Integer.class);
exists = count > 0;

安杰洛


0
投票

如果存在数据库支持(例如Postgres),最好使用它:

String query = "SELECT EXISTS(SELECT * FROM table_name WHERE ...)";
boolean exists = jdbcTemplate.queryForObject(query, params, Boolean.class);

Fastest check if row exists in PostgreSQL

© www.soinside.com 2019 - 2024. All rights reserved.