查询以检查记录是否存在于Spring Jdbc模板中

Shu*_*ubh 3 spring jdbctemplate

我对Spring还是很陌生,我想检查数据库中是否存在某个电子邮件ID,或者不使用Spring Jdbc模板,我在这里查看但找不到正确的答案。SELECT count(*) from table where email=?

任何帮助将不胜感激。

Adi*_*tya 6

如果您使用的是jdbctemplate新版本的,则可以执行以下操作spring

private boolean isEmailIdExists(String email) {
    String sql = "SELECT count(*) FROM table WHERE email = ?";
    boolean result = false;
    int count = jdbcTemplate.queryForObject(sql, new Object[] { email }, Integer.class);
    if (count > 0) {
      result = true;
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

queryForObject方法jdbcTemplate接受sql查询作为第一个参数,第二个参数是sql查询占位符的对象数组,第三个参数是sql查询的预期返回值。

在这种情况下,我们只有一个占位符,因此我给出了第二个参数,new Object[] { email }并且我们期望的结果是一个整数,因此我给出了Integer.class

我有点从https://www.mkyong.com/spring/jdbctemplate-queryforint-is-deprecated/得到了这个答案

如果您有兴趣,可以阅读一下。