Connect R to a SQL Server database engine

元气小坏坏 提交于 2019-11-27 06:55:46

问题


At my work I have R-Studio (Microsoft R Open 3.2.5) installed and would like to connect to a Microsoft SQL Server database, to run scripts using the tables I have.

Is there any chance that I can connect to a SQL Server database using Pentaho and then using the object Execute R-Script to make an OLAP Cube? Do I need a package to connect SQL engine? What would be the steps to perform?

I already have the snowflake arquitectura of the data base. With the fact table and the state tables. But I do not know where to start.


回答1:


You can connect to SQL Server directly from R using at least 4 libraries (RODBC, rsqlserver, RSQLServer, RJDBC).

As long as you have enough RAM, you can import your data into R and do your analysis there using for example amazing dplyr or data.table packages. On the other hand, you can just connect to SQL Server and send SQL queries to the server and do your data wrangling inside your database and then import results to R for further (statistical) analysis and visualization.




回答2:


Something like this should work:

library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=YourDBName\\SQLEXPRESS; Database=TestDB;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(dbconnection)

Check out these links:

RODBC odbcDriverConnect() Connection Error

https://andersspur.wordpress.com/2013/11/26/connect-r-to-sql-server-2012-and-14/

Finally, make sure SQL Server has all proper permissions applied.




回答3:


Here is another way to connect to SQL Server, using Windows creds.

library("RODBC")
#library("XLConnect")

dbhandle <- odbcDriverConnect('driver={SQL Server};server=Name_Of_Server;database=Name_Of_DB;trusted_connection=true')
currTableSQL<-paste("SELECT * From Your_Table",sep="")
currTableDF<-sqlQuery(dbhandle,currTableSQL)

Uncomment the XLConnect if you want to utilize that library. I feel like a lot of times if you are using SQL Server, you are using Excel as well.



来源:https://stackoverflow.com/questions/39401230/connect-r-to-a-sql-server-database-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!