java - 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
解决方案
问题似乎与驱动程序的错误有关。
这两种解决方法都对我有用:
- kayaman 提出:
首先执行sql命令
SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY
- a_horse_with_no_name 提出:
禁用自动提交使 setReadOnly 调用有效
Connection.setAutoCommit(false);
Connection.setReadOnly(true);
推荐阅读
- reactjs - 无法使用 React 挂钩表单获取上传图像值
- angular - 我想使用离子角度显示关于离子输入焦点的建议工具提示
- amazon-cloudformation - AWS Cloud Formation 带有参数的多个路由条目
- vue.js - 如何将tailwind中的图标正确导入vue数组
- html - (使用 scss/css)我的按钮中的动作悬停不起作用
- linux - 无法从 google colab 连接本地运行时
- node.js - Axios 发布请求未得到解决
- python - Plotly Dash 如何强制一个主题中的所有链接
- css - Material UI - 标签没有很好地生成
- c++ - 对`dp_lib_init()`的未定义引用