从R到PostgreSQL,我使用RPostgreSQL包上载带有重音字母的数据框,而在PostgreSQL中查询时,它不显示正确的字符。
# Connection
db_host <- "localhost"
db_port <- db_port_number
db_name <- "db_Name"
db_user <- "db_username"
db_pass <- "password"
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv,
dbname = db_name,
host = db_host, port = db_port,
user = db_user, password = db_pass)
# Check data base encoding
dbGetQuery(con, "SHOW server_encoding;")
# Result: server_encoding
# 1 UTF8
# Data frame
df <- data.frame(Order = 1:3, Name = c("Cía de Cereales", "Compañía Paraná", "Ondulación"))
df <- set_utf8(df)
# Upload
dbWriteTable(con,
"df",
fileEncoding = "UTF-8",
value = df,
append = TRUE,
row.names = FALSE)
dbDisconnect(con)
dbUnloadDriver(drv)
# # Subfunction # #
set_utf8 <- function(x) {
# Declare UTF-8 encoding on all character columns:
chr <- sapply(x, is.character)
x[, chr] <- lapply(x[, chr, drop = FALSE], `Encoding<-`, "UTF-8")
# Same on column names:
Encoding(names(x)) <- "UTF-8"
x
}
SELECT * FROM df;
实际结果:
订购|名称 ------- + ----------------- 1 |谷物谷物 2 | Compa±ßaParanß 3 | Ondulaci¾n (3条)
预期结果:
订购|名称 ------- + ----------------- 1 |谷物谷物 2 | CompañíaParaná 3 | Ondulación (3条)