2017-03-23 6 views
0

現在、データセットを取得するために、すべてのグラフの始めにDB接続を呼び出し、データセットが取得されたら接続を閉じました。ロードされる。DB接続をグローバルに呼び出す方法はありますか?毎回呼び出す必要はありません。

DB接続をグローバルに呼び出す方法があるので、毎回呼び出す必要はありません。私はこれがスピードを向上させると同時に、コードを維持するのが容易であると推測します。

サンプルコード:

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

をあなたはグローバルでそれを持っている可能性があり.Rファイルは、ui.Rとserver.Rと同じフォルダにあります。アプリケーションが起動されたとき(runAppを実行しているとき)にglobal.Rが一度ロードされるので、あなたは 'renderPlot'で使用できるように接続を利用できます。 – LyzandeR

+0

こんにちはLyzanderがコメントしてくれてありがとう。あなたはplsできますか?私はRプログラミングの初心者ですから、サンプルアプリケーションにglobal.Rファイルを提供してください。 – leelavinodh

答えて

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) 
関連する問題