Connect to Salesforce using R

Last modified: July 7, 2025

You can connect to Salesforce from R using Devart ODBC Driver for Salesforce.

Install the odbc package

Run the following command to install the odbc package.

install.packages("odbc")

Define a connection string

An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).

For information about available parameters, see Connection string parameters.

DSN connection string

You can use a connection string with a predefined DSN.

connection_string <- "DSN=your_dsn"

If you need credentials other than those used in the DSN, specify them in the connection string to override the DSN values.

connection_string <- "DSN=your_dsn;User ID=your_username;Password=your_password"

For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.

DSN-less connection string

You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.

The following example uses OAuth 2.0 authentication.

connection_string <- "DRIVER=Devart ODBC Driver for Salesforce;Authentication=OAuth;Refresh Token=your_refresh_token"

For more information, see DSN-less connections.

Connect to Salesforce

The following R code demonstrates how to connect to Salesforce and fetch data using the ODBC driver.

# Load the odbc package
library(odbc)

# Define an ODBC connection string
connection_string <- "your_connection_string"

con <- tryCatch(
  dbConnect(odbc::odbc(), .connection_string = connection_string),
  error = function(e) {
    stop("Connection failed: ", e$message)
  }
)

# Check if the connection is successful
if (!dbIsValid(con)) {
  stop("Connection failed!")
} else {
  print("Connection successful!")
}

# Execute an SQL query to retrieve data from the data source
query <- "SELECT * FROM Account LIMIT 10"
data <- tryCatch(
  dbGetQuery(con, query),
  error = function(e) {
  stop("Query execution failed: ", e$message)
  }
)

# Print the retrieved data
print(data)

# Close the connection
dbDisconnect(con)