如何更改数据库连接区域设置?

How do I change the database connection locale?

在 R 中使用 DBI 包时,我无法更改 "locale"。更具体地说,我的数据库包含“é、è、ê、...”等字符,而 DBI 无法读取他们正确。

当我使用 RODBC 包执行相同的查询时,它确实为我提供了正确的结果。我的问题:如何使用 DBI 包获得正确的结果(即正确读取“é, è, ê, ...”)?

这应该是一个可重现的例子:

sql <- "select * from myDatabase.dbo.myTable"
# Where myTable contains any of the difficult characters

# Try with DBI
library(odbc)
library(DBI)

conDBI <- dbConnect(
  odbc::odbc(),
  dsn   = "myDsn",
  UID   = myLogin,
  PWD   = myPassword,
  Port  = 1433
)

table_DBI <- dbGetQuery(conDBI, sql)

# Try with RODBC
library(RODBC)

conRODBC <- odbcConnect(
  "myDsn",
  uid = myLogin,
  pwd = myPassword
)

table_RODBC <- sqlQuery(conRODBC, sql)

如果这是相关的,这是我的会话信息:

> sessionInfo()
R version 3.4.0 Patched (2017-06-02 r72765)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=Dutch_Belgium.1252  LC_CTYPE=Dutch_Belgium.1252    LC_MONETARY=Dutch_Belgium.1252 LC_NUMERIC=C                  
[5] LC_TIME=Dutch_Belgium.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  tools     methods   base     

other attached packages:
[1] RODBC_1.3-15 DBI_0.6-1    odbc_1.1.1  

loaded via a namespace (and not attached):
[1] bit_1.1-12     compiler_3.4.0 hms_0.3        tibble_1.3.3   Rcpp_0.12.11   bit64_0.9-7    blob_1.1.0     rlang_0.1.1   

您是否尝试过在 dbConnect 函数中使用编码参数?它应该是数据库上使用的文本编码。 "If the database is the same as your local encoding set to "”。有关系统可用编码的完整列表,请参阅 iconvlist()。注意字符串始终以 UTF-8 编码返回。”

你可以试试:

conDBI <- dbConnect( 
odbc::odbc(), 
dsn = "myDsn", 
UID = myLogin, 
PWD = myPassword, 
Port = 1433, 
encoding = "latin1" )

HTH 詹姆斯