首页 > 解决方案 > setReadOnly 不适用于 PostgreSQL 连接

问题描述

我在使用 JDBC 设置与 PostgreSQL 数据库的只读连接时遇到问题。

我正在创建一个应用程序,它加载要从文件执行的查询,并且我只想执行 SELECT(只读)查询。为将运行应用程序的用户设置权限不是一种选择,因此通过该Connection.setReadOnly(boolean)方法在代码级别设置权限是我能想到的唯一选择。

现在的问题是我尝试了我的应用程序进行插入和删除查询并且它们正常运行,所以我的解决方案不起作用。

有关如何解决问题的任何提示?

下面是我正在测试的简单代码片段:

public class Test{

public static void main(String[] args) {
    connectAndExecute();
}

public static void connectAndExecute() {
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
        return;
    }

    Connection connection;

    String connString = "jdbc:postgresql://localhost:5432/testdb";
    try {
        connection = DriverManager.getConnection(connString, "user", "password");
    } catch (SQLException e) {
        e.printStackTrace();
        return;
    }

    try {
        connection.setReadOnly(true);
        connection.createStatement().execute("delete from testtable");
        // connection.createStatement().execute("insert intotesttable(testfield1)values('test')");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

这是我正在使用的 JDBC 驱动程序

<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.10</version>

PostgreSQL 版本:11.6

标签: javapostgresqljdbcreadonly

解决方案


问题似乎与驱动程序的错误有关。

这两种解决方法都对我有用:

  • kayaman 提出:

首先执行sql命令

SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY
  • a_horse_with_no_name 提出:

禁用自动提交使 setReadOnly 调用有效

Connection.setAutoCommit(false);
Connection.setReadOnly(true);

推荐阅读