R 中强制停止查询

问题描述 投票:0回答:1

我在 R 中使用 odbc 从 SQL 服务器获取数据。 最近,我遇到了一个问题:由于某种未知的原因。我的查询可能需要几个小时才能从 SQL 服务器获取结果。以前还好。返回数据只有10000行。我的数据团队同事还没有弄清楚原因。我的旧代码是:

getSqlData = function(server, sqlstr){
con = odbc::dbConnect(odbc(), 
                    Driver = "SQL Server", 
                    Server = server, 
                    Trusted_Connection = "True")
result = odbc::dbGetQuery(con, sqlstr)
dbDisconnect(con)
return(result)
} 

起初,我试图为 dbGetQuery() 找到一个超时参数。不幸的是,这个函数没有这样的参数。所以我决定自己监控运行时间。

getSqlData = function(server, sqlstr){
con = odbc::dbConnect(odbc(), 
                    Driver = "SQL Server", 
                    Server = server, 
                    Trusted_Connection = "True")
result = tryCatch(
{
  a = withTimeout(odbc::dbGetQuery(con, sqlstr), timeout = 600, onTimeout = "error") 
  
  return(a)
},
   error=function(cond) {
      msg <- "The query timed out:"
      msg <- paste(msg,sqlstr,sep = " ")
      error(logger,msg)
      return(NULL)
   },finally={
      dbDisconnect(con)
      }
   )    
 return(result)
} 

如果 dbGetQuery() 在 10 分钟内没有完成,我会强制函数停止。但是,我收到警告消息

In connection_release(conn@ptr) : There is a result object still in use.
The connection will be automatically released when it is closed

我的理解是这意味着查询仍在运行并且连接未关闭。

有没有办法强制关闭连接并强制停止查询?

我注意到的另一件事是,即使我设置 timeout = 1,它也不会在 1 秒内引发错误,它会运行大约 1 分钟,然后引发错误。有谁知道为什么会这样?

谢谢你。

r odbc
1个回答
0
投票

不知道这是否是最好的答案,但我使用 sapply 通过

sapply(dbListConnections(odbc()), dbDisconnect)
注销所有打开的连接,然后再次连接。

© www.soinside.com 2019 - 2024. All rights reserved.