我真的很喜欢DBI的dbWriteTable函数(我通常使用RSQLite或ROracle作为后端)。
我使用该功能导入许多excel电子表格,问题是,如果这些电子表格是在长期列上创建的,则更改会被添加/删除或将名称从一个文档更改为另一个文档。
因此,我的问题是,有人可以相对快速地将数据添加到数据库中而又不必完全匹配归档列表吗?
这是我使用的示例脚本
require(RSQLite)
require(readxl)
# Create database file
conn <- dbConnect(drv=SQLite(),dbname = "path to database")
# Define import function
excel2sqltable <- function(conn, file, table) {
source.df <- read_excel(path=file,col_names = TRUE) %>%
cbind("SourceFile" = file, .)
names(source.df) <- source.df %>%
data.frame(check.names = TRUE) %>%
{gsub("[.]",x=names(.),replacement="_")}
print(paste("Importing ", file))
setOldClass(c("tbl_df", "data.frame"))
dbWriteTable(conn = conn, name = table, value = source.df, append=TRUE)
}
使用该功能,我可以执行以下操作: sapply(list.files(),FUN = function(x){excel2sqltable(conn,x,"Imports")})
您可以以此为指导:
library(RSQLite)
sqlite_conn <- dbConnect(drv = SQLite(),dbname = 'data_dump.sqlite')
excel2sqltable <- function(conn, file, table) {
source.df <- readxl::read_excel(path=file,col_names = TRUE) %>%
cbind("SourceFile" = file, .)
names(source.df) <- source.df %>%
data.frame(check.names = TRUE) %>%
{gsub("[.]",x=names(.),replacement="_")}
if(!dbExistsTable(conn, table)) {
dbWriteTable(conn = conn, name = table, value = source.df)
} else {
# Get both dataframe columns and table columns
df_cols <- colnames(source.df)
tbl_cols <- dbListFields(conn, table)
# Check if there are columns in the dataframe
# that are not in the destination table
# Loop through the missing columns and add
# them to the database table
if (length(setdiff(df_cols, tbl_cols)) > 0) {
missing_cols <- setdiff(df_cols, tbl_cols)
for (col_name in missing_cols) {
dbSendStatement(conn, sprintf('ALTER TABLE %s ADD %s VARCHAR', table, col_name))
}
}
setOldClass(c("tbl_df", "data.frame"))
dbWriteTable(conn = conn, name = table, value = source.df, append=TRUE)
}
}
lapply(list.files(), function(x) {
excel2sqltable(sqlite_conn, x, "Imports")
})
dbDisconnect(sqlite_conn)
我希望它能达到目的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句