在 R 中查询 PostgreSQL 数据库时如何修复警告消息 "Closing open result set, cancelling previous query"?

How do i fix the warning message "Closing open result set, cancelling previous query" when querying a PostgreSQL database in R?

下面是我在 R 中用于从 PostgreSQL 数据库中提取 ID 的代码片段。当我 运行 该函数时,我从 R 收到以下警告消息:

In result_create(conn@ptr, statement) : Closing open result set, cancelling previous query

如何在代码开头不使用 options(warn=-1) 来避免出现此警告消息,从而抑制警告而不是

con <- dbConnect(RPostgres::Postgres(),
                 user = "postgres",
                 dbname  = "DataBaseName",
                 password  = "123456",
                 port  = 5431)


get_id <- function(connection, table){

  query <- toString(paste("SELECT id FROM ", table, sep = ""))
  data_extract_query <- dbSendQuery(connection, query)
  data_extract <- dbFetch(data_extract_query)
  return(data_extract)
}


get_id(con, "users") 

我找到了解决问题的方法

我在 GitHub 上为 RSQLite a https://github.com/r-dbi/RSQLite/issues/143 找到了一个帖子。在此线程中,他们在 dbFetch() 函数中显式设置 n = -1

这似乎解决了我的问题,通过像下面这样编辑代码,警告消息没有再次出现:

data_extract <- dbFetch(data_extract_query, n = -1)

n的意思是查询应该return的行数。通过将其设置为 -1 将检索所有行。默认情况下,它设置为 n = -1 但由于某种原因,在此版本的 R (3.6.3) 中仍会显示警告。

在 R 中调用 ?dbFetch 你可以看到更多相关信息。我在 R-help 页面中包含了一个片段:

Usage

dbFetch(res, n = -1, ...)

fetch(res, n = -1, ...)

Arguments

res An object inheriting from DBIResult, created by dbSendQuery().

n maximum number of records to retrieve per fetch. Use n = -1 or n = Inf to retrieve all pending records. Some implementations may recognize other special values.

... Other arguments passed on to methods.

如果在提交新结果之前未清除结果,则其他数据库实现会出现此问题。来自 DBI::dbSendQuery

的文档

Usage dbSendQuery(conn, statement, ...)

...

Value

dbSendQuery() returns an S4 object that inherits from DBIResult. The result set can be used with dbFetch() to extract records. Once you have finished using a result, make sure to clear it with dbClearResult(). An error is raised when issuing a query over a closed or invalid connection, or if the query is not a non-NA string. An error is also raised if the syntax of the query is invalid and all query parameters are given (by passing the params argument) or the immediate argument is set to TRUE.

要消除警告,必须按如下方式修改 get_id() 函数:

get_id <- function(connection, table){

  query <- toString(paste("SELECT id FROM ", table, sep = ""))
  data_extract_query <- dbSendQuery(connection, query)
  data_extract <- dbFetch(data_extract_query)

  # Here we clear whatever remains on the server
  dbClearResult(data_extract_query)

  return(data_extract)
}

有关更多信息,请参阅帮助中的示例部分。