1

在 R 中使用 DBI 包时,我无法更改“语言环境”。更具体地说,我的数据库包含诸如“é、è、ê、...”之类的字符,而 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   
4

1 回答 1

0

您是否尝试过在 dbConnect 函数中使用 encoding 参数?它应该是数据库上使用的文本编码。“如果数据库与设置为“”的本地编码相同。请参阅 iconvlist() 以获取系统上可用编码的完整列表。注意字符串始终返回 UTF-8 编码。

你可以试试:

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

HTH 詹姆斯

于 2017-10-06T14:55:30.293 回答