我正在尝试使用 Postgres 作为数据库构建一个快速的 JDBC 应用程序,但遇到了一个有趣的问题。
我目前有 2 个表,table1 和 table2。
CREATE TABLE table1
(
a character varying NOT NULL,
b integer NOT NULL,
CONSTRAINT table1_pkey PRIMARY KEY (b)
)
CREATE TABLE table2
(
c character varying NOT NULL,
d integer,
CONSTRAINT table2_pkey PRIMARY KEY (c),
CONSTRAINT table2_d_fkey FOREIGN KEY (d),
REFERENCES table1(b) MATCH SIMPLE
ON UPDATE CSCADE ON DELETE CASCADE
)
作为程序的后端,我正在 SELECT
*
并保留查询中的 ResultSet
。每个表都有 1 行简单值,似乎并不重要它们是什么。
我的语句是使用标志 ResultSet.TYPE_SCROLL_INSENSITIVE
和 ResultSet.CONCUR_UPDATE
创建的。尽管我也尝试过 SCROLL_SENSITIVE。
如果我尝试以下操作(假设 ResultSet rs/rs2
有效并分别指向 table1/table2:
rs.first(); // move to the first row (only row)
rs.updateInt(2, 50); // update our primary key, which is also the cascading fk
// 50 could be any number
print(rs); // Will show the old value
rs.updateRow();
print(rs); // Will show the new value
rs2.refreshRow(); // make sure we get the latest data from table2
print(rs2); // will show the old data?
我希望看到级联带来的新值。如果我退出并重新运行应用程序,而不更改任何输入,那么它将打印正确的 table2 值。我猜这是由于重新运行 SELECT 语句所致。如果我通过运行 psql 或 pgadmin3 查看该表,这些值似乎正在发生变化。所以看来refreshRow()并没有带来最新的东西。有人知道为什么吗?
我正在使用:
- java 1.6_29
- postgresql-9.1-901.jdbc4.jar
如有任何帮助,我们将不胜感激。
最佳答案
我希望你能解决这个问题,因为这是一个老问题,但为了记录,我在这里发布了一个我尝试过并且对我有用的片段:
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
Statement stmt2 = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs2 = stmt2.executeQuery("SELECT * FROM table2");
rs.first(); // move to the first row (only row)
rs.updateInt(2, 50); // update our primary key, which is also the
// cascading fk 50 could be any number
System.out.println(rs.getString(2)); // Prints the old value 12
rs.updateRow();
System.out.println(rs.getString(2)); // Prints the new value 50
rs2.first();
rs2.refreshRow(); // make sure we get the latest data from table2
System.out.println(rs2.getString(2)); // Prints the new value 50
关于java - JDBC ResultSet::RefreshRow 不适用于级联更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9553360/