A
A
avgwowenjoyer2022-04-03 20:24:05
PostgreSQL
avgwowenjoyer, 2022-04-03 20:24:05

How to create a method from a SQL query?

This query in PostrgreSQL returns true if there is such a record in the database and false if not:

SELECT count(*) <> 0 FROM customers
WHERE name = 'Bob' AND purchase = 'bike'

How to create such a method returning boolean in Java?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sergey, 2022-04-04
@avgwowenjoyer

almost the same as:

ResultSet resultSet = statement.executeQuery("SELECT count(*) as cnt FROM customers WHERE name = 'Bob' AND purchase = 'bike'");
  resultSet.next(); // not first() with PGSL JDBC it is forward only cursor
  final int cnt = resultSet.getInt(1);   
  System.out.println("cnt: " + cnt);

keep in mind that you can, of course, execute the original SQL query through JDBC, but its syntax is not standard SQL, this is some kind of postgres extension:
String query = "SELECT count(*) <> 0 FROM accounts WHERE username = 'bob';";
              System.out.println("Executing count query: " + query);
              ResultSet resultSet = connection.createStatement().executeQuery(query);
              resultSet.next();
              final boolean status = resultSet.getBoolean(1);
              System.out.println("status: " + status);

O
Orkhan, 2022-04-03
Hasanly @azerphoenix

Well, perhaps you should clarify whether you are working with jdbc or with Spring JDBC, Spring JPA, Hibernate, etc.
Spring has such a thing as exists*
For example,

existsCustomerByNameAndPurchase(String name, String purchase);

More: https://www.baeldung.com/spring-data-exists-query
Well, if jdbc, then what's the problem? Executed SQL query. Checked the number of records. If greater than 0, then true, if 0 - false

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question