问题描述
我试图使用 ReadOnlyTransaction.getReadTimestamp() 函数,但我一直遇到异常: “方法只能在读取返回数据或完成后调用” 我从数据库返回了一两条记录,但我无法读取时间戳。 以下是我正在做什么和做什么的示例代码。
IO {
val db = spannerClientInstance
val rotxn = db.singleUseReadOnlyTransaction()
val sql = "SELECT " +
"Name " +
"FROM Person " +
"WHERE Name= @Name"
val resultSet = db.singleUse.executeQuery(
Statement.newBuilder(sql).bind("Name").to(name).build()
)
(resultSet,rotxn)
}.bracket {
case (resultSet,rotxn) =>
IO {
val result =
scala.collection.mutable.Map.empty[String,Person]
while (resultSet.next()) {
result += (resultSet.getString(0) -> new Person(resultSet.getString(0)))
}
(result.toMap,rotxn.getReadTimestamp)
}
} {
case (resultSet,_) =>
IO(resultSet.close())
}
我尝试使用 resultSet.close() 和 rotxn.close() 关闭 resultSet 和/或 rotxn,然后调用 rotxn.getReadTimestamp(),但运气不佳。我收到了同样的错误消息。
我正在使用 Spanner Java 库:com.google.cloud:google-cloud-spanner:2.0.1 尝试谷歌搜索这个问题,但没有找到太多。欢迎任何帮助:)
谢谢。 :)
解决方法
看来您实际上并未对您启动的只读事务执行查询。执行查询的代码是:
val resultSet = db.singleUse.executeQuery(
Statement.newBuilder(sql).bind("Name").to(name).build()
)
该查询使用的是一次性只读事务,而不是您之前的只读事务。尝试像这样执行它:
val resultSet = rotxn.executeQuery(
Statement.newBuilder(sql).bind("Name").to(name).build()
)