如何解决Shiny上传.xlsx文件后无法通过RSQLite写入数据库生成新表的问题
Shiny Excel上传写入SQLite数据库修复方案
原代码核心问题
- 外部函数加载错误:
source()默认返回列表,直接赋值无法正确获取Load_Data函数 - 数据传递链路断裂:
Load_Data.R中引用的contents变量未定义,上传的Excel数据没有传入写入逻辑 - 无容错校验:未判断用户是否上传文件、数据库表已存在时直接写入会报错
- 无数据库连接释放逻辑:写入完成后未关闭连接,容易造成连接泄漏
修改后完整代码
1. ui.R(无改动,可直接复用)
navbarPage( "Ingreso de Data a Base de Datos", fileInput('file1', 'Choose xlsx file', accept = c(".xlsx") ), actionButton("Load_DB_Button", "Load Data", style = "bordered", width = "100%"), mainPanel( tableOutput('contents')) )
2. server.R 修改版
library(readxl) # 正确加载外部函数,取source返回的value字段获取定义的函数 Load_Data <- source("Load_Data.R", local = TRUE)$value function(input, output, session){ # 将上传的Excel数据封装为独立响应式变量,方便多处复用 uploaded_df <- reactive({ req(input$file1) read_excel(input$file1$datapath, sheet = 1) }) output$contents <- renderTable({ uploaded_df() }) vals <- reactiveValues() observeEvent(input$Load_DB_Button,{ # 校验数据存在后再执行写入 req(uploaded_df()) vals$Load_Data_Out <- Load_Data(uploaded_df()) showModal(modalDialog("Calculation Finished!")) }) }
3. Load_Data.R 修改版
library(RSQLite) library(dplyr) # 增加数据入参,接收上传的Excel数据 function(df){ # 连接数据库 BD_CA_IDAAN <- DBI::dbConnect(RSQLite::SQLite(), "C:/Users/CBarrios/Desktop/Ex_Files_Data_Apps_R_Shiny/Exercise Files/07_03/Database/DB_CA_IDAAN.db") on.exit(DBI::dbDisconnect(BD_CA_IDAAN)) # 函数执行结束自动关闭数据库连接 # 写入数据库,overwrite=TRUE表示覆盖已有表,需要追加数据可替换为append=TRUE dbWriteTable(BD_CA_IDAAN, "Test_Table", df, overwrite = TRUE) message("Running Code") return("Some Output") }
注意事项
- 如果需要保留历史数据,将
dbWriteTable的overwrite = TRUE替换为append = TRUE即可 - 表名建议不要使用空格,避免SQL查询时额外处理,示例中已改为
Test_Table,如需保留原名可改回Test Table
内容的提问来源于stack exchange,提问作者Carlos Barrios
相关产品推荐
相关产品推荐

