Skip to content
Advertisement

setReadOnly not working on PostgreSQL Connection

I have a problem setting a read-only connection with a PostgreSQL database using JDBC.

I’m creating an application which loads queries to execute from a file, and I want to execute only SELECT (read-only) queries. Setting permissions on users who will run the application is not an option, so setting permissions at code level through the Connection.setReadOnly(boolean) method was the only option I could think of.

Now the problem is that I tried my application for an insert and delete query and they run normally, so my solution does not work.

Any tips on how to solve the problem?

Here below the simple code snippet which I’m testing:

JavaScript

and this is the JDBC driver I’m using

JavaScript

PostgreSQL version: 11.6

Advertisement

Answer

Problem seems related to a bug of the driver.

These two workaround both worked for me:

  • proposed by kayaman:

executing first the sql command

JavaScript
  • proposed by a_horse_with_no_name:

disabling auto-commit makes the setReadOnly call effective

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement