64

I am trying to insert a data into a table. After executing the query i am getting an exception stating

org.postgresql.util.PSQLException: No results were returned by the query.
org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:284)

The data is getting inserted successfully, but i have no idea why i am getting this exception ??

Milen A. Radev
  • 60,241
  • 22
  • 105
  • 110
Ragesh Kr
  • 1,573
  • 8
  • 29
  • 46

6 Answers6

122

Use

executeUpdate

instead of

executeQuery

if no data will be returned (i.e. a non-SELECT operation).

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • Beauty ! works perfectly.. but y is it like executeUpdate works but executeQuery doesnt work ?? in both casesdata is getting inserted properly. – Ragesh Kr Jan 22 '14 at 07:15
  • 1
    @RageshKr, it gets inserted correctly, but the Java database connector is afterwards expecting data, and none comes. So the error happens after the insert. – Paul Draper Dec 26 '14 at 17:09
35

Please use @Modifying annotation over the @Query annotation.

@Modifying
@Query(value = "UPDATE Users set coins_balance = coins_balance + :coinsToAddOrRemove where user_id = :user_id", nativeQuery = true)
    int updateCoinsBalance(@Param("user_id") Long userId, @Param("coinsToAddOrRemove") Integer coinsToAddOrRemove); 

The same is true for any DML query (i.e. DELETE, UPDATE or INSERT)

Ricardo
  • 3,696
  • 5
  • 36
  • 50
12

Using @Modifying and @Transaction fixed me

Shahid Hussain Abbasi
  • 2,508
  • 16
  • 10
5

The problem that brought me to this question was a bit different - I was getting this error when deleting rows using an interface-based Spring JPA Repository. The cause was that my method signature was supposed to return some results:

@Modifying
@Query(value = "DELETE FROM table t WHERE t.some_id IN (:someIds)", nativeQuery = true)
List<Long> deleteBySomeIdIn(@Param("someIds") Collection<Long> someIds);

Changing the return type to void resolved the issue:

@Modifying
@Query(value = "DELETE FROM table t WHERE t.some_id IN (:someIds)", nativeQuery = true)
void deleteBySomeIdIn(@Param("someIds") Collection<Long> someIds);
JohnEye
  • 6,436
  • 4
  • 41
  • 67
2

If you want last generated id, you can use this code after using executeUpdate() method

 int update = statement.executeUpdate()
 ResultSet rs = statement.getGeneratedKeys();
 if (rs != null && rs.next()) {
  key = rs.getLong(1);
 }
Popeye
  • 253
  • 4
  • 13
0

I have solved this Problem using addBatch and executeBatch as following:

statement.addBatch("DELETE FROM public.session_event WHERE id = " + entry.getKey());
statement.executeBatch();
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61