目前,我已在每个图表的开头调用数据库连接以获取数据集,并在加载数据集后关闭连接。
有没有办法全局调用数据库连接,所以我们不必每次都调用它。我认为这会提高速度,同时代码也很容易维护。
示例代码:
output$moveyear1 <- renderPlot({
#DB connection
con = dbConnect(MySQL(), user='', password='', db='', host='')
# query to fetch data.
query = paste("select * from table1 ",sep="")
result = dbGetQuery(con, query)
dbDisconnect(con)
# draw the graph
ggplot(result, aes(gameYear,DEPARTMENT_NAME)) +
geom_tile(color="white", size=0.1,aes(fill=MoveCount))+
facet_wrap(~TEAM_ID) + labs(x="GameYear") + ggtitle("Total Move made in a Year")
}})
output$avgtt <- renderPlot({
#DB connection
con = dbConnect(MySQL(), user='', password='', db='', host='')
# query to fetch data.
query = paste("select * from table2",sep="")
result = dbGetQuery(con, query)
dbDisconnect(con)
# draw the graph
ggplot(result, aes(gameYear,DEPARTMENT_NAME)) +
geom_tile(color="white", size=0.1,aes(fill=AvgTT))+
facet_wrap(~TEAM_ID) + labs(x="GameYear") + ggtitle("Average Time taken for Move")
}})
答案 0 :(得分:1)
将其放在名为global.R的文件中,或者将其放在服务器和ui函数之外:
library(DBI) ##or whichever one you're using
#DB connection
con = dbConnect(MySQL(), user='', password='', db='', host='')
# query to fetch data.
query = paste("select * from table1 ",sep="")
result1 = dbGetQuery(con, query)
dbDisconnect(con)
#leave the connection open if they're from the same place
#DB connection
con = dbConnect(MySQL(), user='', password='', db='', host='')
# query to fetch data.
query = paste("select * from table2",sep="")
result2 = dbGetQuery(con, query)
dbDisconnect(con)
ui <- fluidPage(
# Application title
titlePanel("Your App"),
# Sidebar with a slider input for number of bins
sidebarLayout(),
# Show a plot of the generated distribution
mainPanel(
plotOutput("moveyear1"),
plotOutput("avgtt")
)
)
)
server <- shinyServer(function(input, output, session) {
output$moveyear1 <- renderPlot({
ggplot(result1, aes(gameYear,DEPARTMENT_NAME)) +
geom_tile(color="white", size=0.1,aes(fill=MoveCount))+
facet_wrap(~TEAM_ID) + labs(x="GameYear") + ggtitle("Total Move made in a Year")
})
output$avgtt <- renderPlot({
ggplot(result2, aes(gameYear,DEPARTMENT_NAME)) +
geom_tile(color="white", size=0.1,aes(fill=AvgTT))+
facet_wrap(~TEAM_ID) + labs(x="GameYear") + ggtitle("Average Time taken for Move")
})
shinyApp(ui = ui , server = server)