Connect to MSSQL using DBI - r

I can not connect to MSSQL using DBI package.
I am trying the way shown in package itself
m <- dbDriver("RODBC") # error
Error: could not find function "RODBC"
# open the connection using user, passsword, etc., as
# specified in the file \file{\$HOME/.my.cnf}
con <- dbConnect(m, dsn="data.source", uid="user", pwd="password"))
Any help appreciated. Thanks

As an update to this question: RStudio have since created the odbc package (or GitHub version here) that handles ODBC connections to a number of databases through DBI. For SQL Server you use:
con <- DBI::dbConnect(odbc::odbc(),
driver = "SQL Server",
server = <serverURL>,
database = <databasename>,
uid = <username>,
pwd = <passwd>)
You can also set a dsn or supply a connection string.

It looks like there used to be a RODBC driver for DBI, but not any more:
http://cran.r-project.org/src/contrib/Archive/DBI.RODBC/
A bit of tweaking has got this to install in a version 3 R but I don't have any ODBC sources to test it on. But m = dbDriver("RODBC") doesn't error.
> m = dbDriver("RODBC")
> m
<ODBCDriver:(29781)>
>
Suggest you ask on the R-sig-db mailing list to maybe find out what happened to this code and/or the author...

Solved.
I used library RODBC. It has great functionality to connect sql and run sql queries in R.
Loading Library:
library(RODBC)
# dbDriver is connection string with userID, database name, password etc.
dbhandle <- odbcDriverConnect(dbDriver)
Running Sql query
sqlQuery(channel=dbhandle, query)
Thats It.

Related

Connect to teradata using DBI Package in R

Can you anyone help me with how to connect to Teradata using DBI ODBC Package?
I use the code below,
con <- dbConnect( drv = dbDriver('Teradata'),
server=prodServer,
DBCName=prodDatabaseName,
uid=username,
pwd=password,
MechanismName = TD2)
but it throws the following error:
Error: Couldn't find driver Teradata. Looked in:
* global namespace
* in package called Teradata
* in package called RTeradata
Looks like Teradata ODBC driver, DBCName is a network name (which for other drivers would typically supplied as Server)
con <- dbConnect(odbc::odbc(),
Driver = DRIVER,
DBCName = SERVER,
Database = defaultDatabase,
UID = Sys.getenv("tera_user"),
PWD = Sys.getenv("tera_pass"))
After quite a looot of research, I finally found this in an answer by #Fred to another question:
R-Studio - connection to Teradata is not working

Connection from Access to R via DBI

I am looking to analyse data in R (using dplyr) contained in an Access database on my laptop. (My first time trying to set up a database connection in R.)
Looking at the tidyverse site, for dplyr to work on the Access data, it seems that the connection must be via the DBI package (rather than RODBC).
I'm struggling with the syntax of dbConnect.
My code for RODBC was
base1<-odbcDriverConnect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=[filepath]/AdventureWorks DW 2012.accdb")
My (failed) attempt for DBI is
DB <- dbConnect(drv=Microsoft Access Driver (*.mdb, *.accdb)), host=[filepath]/AdventureWorks DW 2012.accdb)
What am I doing wrong?
(I'm working on Windows 10 - everything 64 bit.)
I recently needed to convert my RODBC defined db connections to equivalent DBI connections. Here's the original RODBC function:
connect_to_access_rodbc <- function(db_file_path) {
require(RODBC)
# make sure that the file exists before attempting to connect
if (!file.exists(db_file_path)) {
stop("DB file does not exist at ", db_file_path)
}
# Assemble connection strings
dbq_string <- paste0("DBQ=", db_file_path)
driver_string <- "Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
db_connect_string <- paste0(driver_string, dbq_string)
myconn <- odbcDriverConnect(db_connect_string)
return(myconn)
}
As explained here, the dbplyr package is built from the DBI package. The first argument of the DBI::dbConnect() must be an appropriate back-end driver. See the link for a list of drivers. For Access, the odbc::odbc() driver is suitable. The second argument the dbConnect function is the full connection string as used in the previous odbcDriverConnect call. With that in mind the following function should connect to your access database:
connect_to_access_dbi <- function(db_file_path) {
require(DBI)
# make sure that the file exists before attempting to connect
if (!file.exists(db_file_path)) {
stop("DB file does not exist at ", db_file_path)
}
# Assemble connection strings
dbq_string <- paste0("DBQ=", db_file_path)
driver_string <- "Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
db_connect_string <- paste0(driver_string, dbq_string)
myconn <- dbConnect(odbc::odbc(),
.connection_string = db_connect_string)
return(myconn)
}
The odbc package documentation presents a more nuanced example as well:
https://github.com/r-dbi/odbc#odbc
As explained here, you can still use odbcConnectAccess2007() but need 32-bit MS Access 2007 drivers from here. This worked great for me.
I just used this a couple days ago.
library(RODBC)
# for 32 bit windows
# Connect to Access db
# channel <- odbcConnectAccess("C:/Users/Excel/Desktop/Coding/Microsoft Access/Northwind.mdb")
# Get data
# data <- sqlQuery( channel , paste ("select * from Name_of_table_in_my_database"))
# for 64 bit windows
channel <- odbcDriverConnect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:/Users/Excel/Desktop/Coding/Microsoft Access/Northwind.mdb")
data <- sqlQuery( channel , paste ("select * from CUSTOMERS"))
odbcCloseAll()

connecting form R (client) to Greenplum server

I'm trying to retrieve data from greenplum cluster into R (win client).
I've tried:
library("RODBC")
conn <- odbcDriverConnect("DSN_name")
Sql <- "select * from DB.st.country"
cen_data <- sqlQuery(conn,Sql)
print(cen_data)
I'm getting error:
0A000 7 ERROR: cross-database references are not implemented
I have seen some answers about dblink but when I tried:
sql <- "select dblink_connect('conn', 'dbname=myDB');"
cen_data <- sqlQuery(conn,Sql)
I'm getting error:
"42883 7 ERROR: function dblink_connect(unknown, unknown) does not exist
Does anyone have any idea what Am I doing wrong?
Instead of ODBC, you can also use the RPostgreSQL package, which uses DBI as the backend.
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, host="hostname", user=..., pass=...)
This is not an R issue (syntax is ok).
The problem was in database definitions.
You need to have the database in the "select data source". for that you need to have postgreSQL.

Connect R and Vertica using RODBC

This is my first time connecting to Vertica. I have already connected to a MySQL database sucessfully by using RODBC library.
I have the database setup in vertica and I installed the windows 64-bit ODBC driver from https://my.vertica.com/download-community-edition/
When I tried to connect to vertica using R, I get the below error:
channel = odbcDriverConnect(connection = "Server=myserver.edu;Database=mydb;User=mydb;Password=password")
Warning messages:
1: In odbcDriverConnect(connection = "Server=myserver.edu;Database=mydb;User=mydb;Password=password") :
[RODBC] ERROR: state IM002, code 0, message [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
2: In odbcDriverConnect(connection = "Server=myserver.edu;Database=mydb;User=mydb;Password=password") :
ODBC connection failed
Can someone tell me how to fix this? Or is there any other ways to connect to vertica using R?
It may not be the fastest, but I prefer to use the Vertica JDBC driver from R. Getting the ODBC drivers working is a little messy across different operating systems. If you already have a Java Runtime Environment (JRE) installed for other applications then this is fairly straightforward.
Download the Vertica JDBC drivers for your Vertica server version from the MyVertica portal. Place the driver (a .jar file) in a reasonable location for your operating system.
Install RJDBC into your workspace:
install.packages("RJDBC",dep=TRUE)
In your R script, load the RJDBC module and create an instance of the Vertica driver, adjusting the classPath argument to point to the location and filename of the driver you downloaded:
library(RJDBC)
vDriver <- JDBC(driverClass="com.vertica.jdbc.Driver", classPath="full\path\to\driver\vertica_jdbc_VERSION.jar")
Make a new connection using the driver object, substituting your connection details for the host, username and password:
vertica <- dbConnect(vDriver, "jdbc:vertica://host:5433/db", "username", "password")
Then run your SQL queries:
myframe = dbGetQuery(vertica, "select Address,City,State,ZipCode from MyTable")
You have to use double slash in the classPath arguement in JDBC function.
for example,
vDriver <- JDBC(driverClass="com.vertica.jdbc.Driver",
classPath="C:\\Program Files\\Vertica Systems\\JDBC\\vertica-jdk5-6.1.2-0.jar")
worked for me, while just copying and pasting the route failed.

R DBI / RPostgreSQL-- connection succeeds but dbListTables returns no tables

The following code connects to my PostgreSQL database successfully (or appears to, at any rate), but attempt to issue queries were met with "relation does not exist" errors, so I tried dbListTables, which doesn't return any tables at all. The database name passed to dbConnect is correct, and the tables do exist. I think the code I'm using is exactly the same as what I was using recently, which worked successfully. Any ideas?
> library(RPostgreSQL)
Loading required package: DBI
> drv <- dbDriver("PostgreSQL")
> con <- dbConnect(drv, dbname="mydb", user="user", password=password)
> dbListTables(con)
character(0)
I'm new to both R and DBI, so I'm sure I could be missing something extremely simple...any help would be appreciated.
Solved-- I was right; it was something incredibly simple (and very, very stupid) on my part. I was running the script from the wrong server. The server I was running it from has an empty copy of the database I was attempting to connect to, so everything succeeded, and the empty result from dbListTables was correct. Once I switched servers (or simply specified the host on the other server), everything worked.
1.Connet to MySQL
a)if Mysql is installed in your system, if not install it.
b)download the RMySQL IN R
library(RMySQL)
drv = dbDriver("MySQL 5.0.1")
make sure MySQL version is correct.
con = dbConnect(drv,host="localhost",dbname="test",user="root",pass="root")
use local host or use the server i.e ip address
use the required database name, user name and password
album = dbGetQuery(con,statement="select * from table")
run required query
close(con)
2.Another way to connect database
a)first install any database like MySQL,Oracle,SQL Server
b)install the ODBC connector for database
library(Rodbc)
channel <- odbcConnect("test", uid="ripley", pwd="secret")
test is the connection name of odbc conector which user has to set manualy
user can find this in Administrator tool
res <- sqlFetch(ch, "table name")
A table can be retrieved as a data frame
res<-sqlQuery(channel, paste("select query"))
part of the with condition one table can be retrieved as a data frame
sqlSave(channel, dataframe)
to save a dataframe to the database(dont use "res<-" something like this)
like user can use
sqlCopy()
sqlDrop()
sqlTables()
close(channel)
always close the connection

Resources