簡體   English   中英

在 ROracle 中編碼

[英]Encoding in ROracle

我在使用 ROracle 從 Oracle 數據庫導入 æ、ø 和 å 等挪威字符時遇到問題。 我以前在 RODBC 上遇到過類似的問題。 從 csv 和 xlsx 等文件導入時我沒有問題,我確定問題出在使用 ROracle 導入時設置編碼,但文檔並沒有真正告訴我如何做到這一點。

各種答案寫了一個 function 用於在導入后轉換為 UTF-8,但這不是適合我的解決方案。 我希望使用 dplyr package 查詢 oracle 數據庫,並且需要能夠使用像æøå這樣的字母進行查詢。

這是我的連接字符串,以及我用作測試的 sql 查詢:

library(ROracle)

drv <- dbDriver("Oracle", unicode_as_utf8 = TRUE, ora.attributes = TRUE)
# Create the connection string
host <- "xx.xxx.xx.x"
port <- xxxx
sid <- "xxxxxx"
connect.string <- paste(
  "(DESCRIPTION=",
  "(ADDRESS=(PROTOCOL=tcp)(HOST=", host, ")(PORT=", port, "))",
  "(CONNECT_DATA=(SID=", sid, ")))", sep = "")
con <- dbConnect(drv, username = "",
                 password = "",dbname=connect.string)

test <- dbGetQuery(con, "SELECT DECODE FROM T_CODE where key_id=17")

這給了我這樣的結果: R?dgivningskontor

這是我的 session 信息:

R version 3.5.0 (2018-04-23)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.4

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

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

other attached packages:
[1] ROracle_1.3-1 DBI_1.0.0    

loaded via a namespace (and not attached):
[1] compiler_3.5.0 tools_3.5.0    yaml_2.1.19  

我已經為這個問題苦苦掙扎了 2 天,但我剛剛找到了解決方案。

我的問題是正確顯示“ü”或“é”等字符(出於測試目的,我還添加了“ø”,顯示為“?”)。 我試圖以不同的方式和不同的字符集設置 NLS_LANG 環境變量。

最后,這些是對我有用的步驟:

  1. NLS_LANG="AMERICAN_AMERICA.AL32UTF8"添加到.Renviron文件。 這適用於我的情況,Oracle DB 顯示NLS_CHARACTERSET=WE8ISO8859P15 ,客戶端的區域設置 ID 顯示en_US.UTF-8
  2. 保存文件並重新啟動 RStudio 會話。

再次運行和查詢數據庫時,此時字符顯示正確。

無法評論,所以我寫這個作為答案。

.Renviron解決方案適用於西班牙數據庫,但是當我使用NLS_LANG="AMERICAN_AMERICA.AL32UTF8"時,我收到了密碼和用戶名錯誤。

然后我找到這篇文章,終於明白了,我的解決方案是。

# First with 'usethis' library create the .Renviron
library(usethis)
usethis::edit_r_environ()

# Then add the NLS_LANG in Renviron
# NLS_LANG=".WE8ISO8859P1"

# If for some reason Renviron wont load you can use this in your script
readRenviron("path_to_the_file/.Renviron")

當然重啟 RStudio 我終於可以得到ñ字符而不是? 符號。

感謝@Ion Garaicoechea

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM