Reading From SQL Databases
Reading From SQL Databases
I The package RODBC is used to read SQL databases (and other database
formats).
I Load required package
> library(RODBC)
Function Description
odbcDriverConnect() Open a connection to an ODBC database
Submit a query to an ODBC database
sqlQuery()
and return the results
sqlTables() List Tables on an ODBC Connection
Read a table from an ODBC database
sqlFetch()
into a data frame
sqlColumns() Query Column Structure in ODBC Tables
close(connection) Close the connection
Connecting to SQL server databases
I Replace server name with the SQL server name on the local machine;
I With the default SQL installation, this is equal to the name of the local
machine:
>connStr <- paste(
+ "Server=My_Machine",
+ "Database=DAT209x01",
+ "uid=Rlogin",
+ "pwd=P@ssw0rd",
+ "Driver={SQL Server}",
+ sep=";"
+ )
I Example
> df <- sqlQuery(conn,
+ "SELECT AVG(Revenue), STDEV(Revenue), Zip
+ FROM bi.salesFact
+ GROUP BY Zip"
+ )
> colnames(df) <- c("AVG(Revenue)", "STDEV(Revenue)", "Zip")
End of session