DBI::dbConnect() 在使用 source() 调用时似乎无法连接

DBI::dbConnect() doesn't seem to connect when called with source()

学习使用odbc包,刚好碰了个小绊脚石。我在名为 conn_to_db.R. 的脚本中有代码(如下) 当我在控制台中 运行 conn_to_db.R 时,连接会在 RStudio 的连接 window 中弹出,我可以 运行 查询等

似乎当我在另一个 R 脚本中使用 source("conn_to_db.R") 调用它时,连接没有发生。该脚本显示为 运行(如果我要求它打印东西,它会打印)。为什么它不连接到 SQL 服务器?

编辑 似乎连接已建立,但当 运行 和 source() 时它不会出现在 RStudio 的连接窗格中,而当我 运行 通过控制台使用相同的行时它会出现。

RStudio 信息:版本 1.2.5001 内部版本 1440(7b3fe265,2019-09-18)

#conn_to_db.R looks like this

library(odbc)
library(DBI)



#save user and password in a file not on git
source("USER.R")
source("PW.R")


#connect to DB
con <- DBI::dbConnect(odbc::odbc(),
                  Driver = "/usr/local/lib/libmsodbcsql.17.dylib"
                 , Server = "working_IP_Address"
                 , PWD = PW 
                 , Port = 1433)


cat("recall when done good practice to close connection. 
      \nAlso, sometimes useful to clear the result of a query, e.g. here a query called \`stu\` 
      \n# clear results dbClearResult(stu)
      \n# close connection dbDisconnect(con)")

最后(post 聊天),连接已建立但未显示在 RStudio 的 "Connections" 窗格中。不过,该对象确实显示在环境中,因此连接是实时的,后续查询按预期工作。