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

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

There is a newer version: 0.0.12
Show 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.List;

public class SelectFirstOrNull implements ConnectionCallback {

  private final String sql;
  private final List sqlParams;
  private final ResultConverter resultConverter;

  public SelectFirstOrNull(String sql, List sqlParams, ResultConverter resultConverter) {
    this.sql = sql;
    this.sqlParams = sqlParams;
    this.resultConverter = resultConverter;
  }

  @Override
  public T 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 resultConverter.convert(rs);
      }
    }

  }
}