3 Introduction to database connections
3.1 Connect with the Connections pane
Connect using the features of the RStudio IDE
- The connections pane (top right hand corner of the RStudio IDE) can guide through establishing database connections.
3.2 Connecting via DSN
Connect using defined Data Source Name (DSN). This requires an ODBC driver.
Load the
DBI
andodbc
packagesUse
odbcListDatasources
to list available DSNsUse
dbConnect
to connect to a database using theodbc
function and a DSNDisconnect using
dbDisconnect
3.3 Connect with a connection string
Connect by specifying all connection details in dbConnect
Use
dbConnect
andodbc
to connect to a database, but this time all connection details are providedDisconnect using
dbDisconnect
3.4 Secure connection details
Use config
, keyring
, or environment variables to secure connection credentials
Load the
config
packageGet the current config using the
get
function and store the results in an object calledconfig
Use
str
to investigate the contents ofconfig
Connect using details provided in
config
Disconnect using
dbDisconnect
Load the
keyring
packageStore the database username and password using
keyring
. The username isrstudio_dev
and the password isdev_user
Use the stored credentials along with
dbConnect
to connect to the databaseDiscnonnect using
dbDisconnect
The
.Renviron
file contains entries to create environment variables forPG_USER
andPG_PWD
. These variables can be read usingSys.getenv()
.Connect to the database using the credentials stored in
.Renviron
andSys.getenv()
Disconnect using
dbDisconnect
Store connection details using
options()
Connect using the credentials accessed via
getOption
Disconnect using
dbDisconnect
Interactively prompt users for input using
rstudioapi::askForPassword()
Disconnect using
dbDisconnect