All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kz.greetgo.security.session.jdbc.SelectIntOrNull Maven / Gradle / Ivy

The newest version!
package kz.greetgo.security.session.jdbc;

import kz.greetgo.db.ConnectionCallback;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class SelectIntOrNull implements ConnectionCallback {

  private final String sql;
  private final List sqlParams;

  public SelectIntOrNull(String sql, List sqlParams) {
    this.sql = sql;
    this.sqlParams = sqlParams;
  }

  public SelectIntOrNull(String sql) {
    this(sql, new ArrayList<>());
  }

  @Override
  public Integer doInConnection(Connection con) throws Exception {
    try (PreparedStatement ps = con.prepareStatement(sql)) {
      int index = 1;
      for (Object param : sqlParams) {
        ps.setObject(index++, param);
      }
      try (ResultSet rs = ps.executeQuery()) {
        if (!rs.next()) return null;
        return rs.getInt(1);
      }
    }
  }
}