我在查询中使用了此方法而没有使用连接,并且它按预期工作。但是我添加了一个内连接,现在它无法更新"使用过的"柱
public HashMap<String, Comparable> getPhoneNumberAndMarkAsUsed() {
String[] colNames = { "phone_number.id", "phone_number.phone_number",
"phone_number.account_id", "phone_number.used AS used",
"(now() AT TIME ZONE account.timezone)::time AS local_time" };
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";
HashMap<String, Comparable> account = new HashMap<String, Comparable>();
try (Connection conn = DriverManager.getConnection(url, props); // Make sure conn.setAutoCommit(false);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query)) {
conn.setAutoCommit(false);
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
// Get the current values, if you need them.
account.put("phone_number", rs.getString("phone_number"));
account.put("account_id", rs.getLong("account_id"));
rs.updateBoolean("used", true);
rs.updateRow();
}
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
循环打印以下
7223 id, 10001234567 phone_number, 1093629 account_id, f used, 23:32:42.502472 local_time
按照上面的输出,然后我使用那个列&#34;使用&#34;是ResultSet的一部分。但我得到以下例外
org.postgresql.util.PSQLException: ERROR: column "used" of relation "account" does not exist
这是打印时的查询
select phone_number.id, phone_number.phone_number, phone_number.account_id, phone_number.used AS used, (now() AT TIME ZONE account.timezone)::time AS local_time from account INNER JOIN phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update
used
属于phone_number
表,而不属于account
表。怎么解决这个问题?
答案 0 :(得分:1)
这是代码中的问题:
rs.updateBoolean("used", true);
此语句将尝试通过结果集更新表的数据,但为此,您无法用户加入,也存在一个问题。 当您通过结果集进行更新时,它将尝试更新帐户表,如果我们发现使用的列是帐户表,则会发生错误。
因此您的代码正在尝试查找列&#34;使用&#34;在帐户表中,但它不存在。
试试这个:
String query = "select " + Stream.of(colNames).collect(Collectors.joining(", "))
+ " from phone_number INNER JOIN account phone_number ON account.id = phone_number.account_id where phone_number.used = false order by id DESC limit 1 for update";