【发布时间】:2021-07-17 16:47:56
【问题描述】:
我正在尝试使用 RShiny 接口连接本地数据库。这个想法是运行查询并因此获得格式良好的表格。
我写的代码是:
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
# Define UI for application that draws a histogram
ui = fluidPage(
selectInput(inputId = "table_name",
label = "Select table",
choices = c("Table_ID" = "Table_name", "Table_ID2" = "Table_name2")
),
fluidRow(
column(12,
tableOutput('table')
)
)
)
server = function(input, output) {
mydb = dbConnect(MySQL(),
user = 'root',
password = 'password',
dbname = 'dbname',
port = 3306
)
Record = reactive( {dbSendQuery(mydb, paste ("select * from", input$table_name, sep = " "))})
data.frame = as.data.frame(fetch(Record))
output$table <- renderTable(data.frame)
}
# Run the application
shinyApp(ui = ui, server = server)
当有稳定的固定值时,我设法让它工作。但是,一旦我尝试交互,应用就会崩溃并返回以下错误。
Listening on http://127.0.0.1:7410
Warning: Error in <Anonymous>: unable to find an inherited method for function ‘fetch’ for signature ‘"reactiveExpr", "missing"’
51: stop
50: <Anonymous>
49: fetch
47: server [server path]
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘fetch’ for signature ‘"reactiveExpr", "missing"’
在另一篇文章中,建议使用 dbGetQuery 而不是 dbSendQuery。就我而言,如果我将代码替换为:
server = function(input, output) {
mydb = dbConnect(MySQL(),
user = 'root',
password = 'N355un4!?',
dbname = 'breeding',
port = 3306
)
Record = dbGetQuery(mydb, paste ("select * from", input$table_name, sep = " "))
output$table <- renderTable(as.data.frame(Record))
}
我得到另一个错误,即:
Listening on http://127.0.0.1:7410
Warning: Error in as.data.frame.default: cannot coerce class ‘c("reactiveExpr", "reactive", "function")’ to a data.frame
99: stop
98: as.data.frame.default
96: renderTable
95: func
82: renderFunc
81: output$table
1: runApp
有什么线索吗?
【问题讨论】:
-
如果在
renderTable中使用as.data.frame(fetch(Record()))是否有效? -
这能回答你的问题吗? RMySQL fetch - can't find inherited method
-
如果我这样做,应用程序不会崩溃,但错误仍然存在。
-
@Luuk 没有。如果我用 dbGetQuery 替换 dbSendQuesry,我会收到一条错误消息,告诉我我无法将结果强制转换为数据帧。所以我应该保留获取过程。
-
当您使用
Record = reactive({fetch(dbSendQuery(mydb, paste0("select * from", input$table_name)))})并使用output$table <- renderTable(Record())时会发生什么