2015-04-27 67 views
1

我無法從knitr塊查詢SQL數據庫。我可以建立連接,查詢在R會話中工作,但在從RStudio編織時會無限期掛起。knitr和SQL查詢


--- 
title: "Untitled" 
author: "XXXXX XXXXXXXXX" 
date: "Monday, April 27, 2015" 
output: html_document 
--- 

TEST TEST 

```{r} 

library(RJDBC) 

jd<-JDBC(driverClass = "com.osisoft.jdbc.Driver",classPath = "C://Program Files (x86)//PIPC//JDBC//PIJDBCDriver.jar") 

piDB<-dbConnect(drv = jd,"jdbc:pisql://XX.XXX.XX.XX/Data Source=XXX;Integrated Security=SSPI") 

sql1<-"SELECT * FROM pipoints" 

sql.dat <- dbGetQuery(piDB, sql1) 

dbDisconnect(piDB) 

print('Success') 
``` 

回答

0

如果你可以使用不同的連接驅動程序,嘗試ODBC。

RODBC正常工作與knitr在RStudio:

```{r} 
library(RODBC) 
myconn = odbcConnect('myServer') 
myquery = paste0("")      #add some query 
data = sqlQuery(myconn, myquery) 
head(data) 
``` 
+0

在一個側面說明,在很多情況下人們可以使用DSN的連接,即沒有設置ODBC條目。也許,[這可能有所幫助](https://techsupport.osisoft.com/Troubleshooting/KB/3234OSI8)。 – mlt

0

隨着RStudio V1.0,你現在可以直接從您的RMarkdown或RNotebook使用SQL塊。我爲此使用odbc軟件包。我喜歡這樣做,因爲它避免了在項目中硬編碼登錄細節,同時仍然創建無需用戶輸入端到端運行的項目。下面

一個RMarkdown例如:

```{r} 
# Unfortunately, odbc is not on CRAN yet 
# So we will need devtools 
# install.packages(devtools) 
library(devtools) 
devtools::install_github("rstats-db/odbc") 

# Get connection info from the Windows ODBC Data Source Administrator using the name you set manually. 
# If you don't know what this is, just search in the windows start menu for  "ODBC Data Source Administrator" 
con <- dbConnect(odbc::odbc(), 'MyDataWarehouse') 
``` 

```{sql connection = con, output.var = result} 
-- This is sql code, comments need to be marked accordingly 
SELECT * FROM SOMETABLE LIMIT 200; 
``` 

```{R} 
# And the result is available in the next chunk! 
result 
```