knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

DBI

Lifecycle: stable rcc Coverage Status CRAN_Status_Badge CII Best Practices

The DBI package helps connecting R to database management systems (DBMS). DBI separates the connectivity to the DBMS into a "front-end" and a "back-end". The package defines an interface that is implemented by DBI backends such as:

and many more, see the list of backends. R scripts and packages use DBI to access various databases through their DBI backends.

The interface defines a small set of classes and methods similar in spirit to Perl's DBI, Java's JDBC, Python's DB-API, and Microsoft's ODBC. It supports the following operations:

Installation

Most users who want to access a database do not need to install DBI directly. It will be installed automatically when you install one of the database backends:

You can install the released version of DBI from CRAN with:

install.packages("DBI")

And the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("r-dbi/DBI")

Example

The following example illustrates some of the DBI capabilities:

library(DBI)
# Create an ephemeral in-memory RSQLite database
con <- dbConnect(RSQLite::SQLite(), dbname = ":memory:")

dbListTables(con)
dbWriteTable(con, "mtcars", mtcars)
dbListTables(con)

dbListFields(con, "mtcars")
dbReadTable(con, "mtcars")

# You can fetch all results:
res <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
dbFetch(res)
dbClearResult(res)

# Or a chunk at a time
res <- dbSendQuery(con, "SELECT * FROM mtcars WHERE cyl = 4")
while (!dbHasCompleted(res)) {
  chunk <- dbFetch(res, n = 5)
  print(nrow(chunk))
}
dbClearResult(res)

dbDisconnect(con)

Class structure

There are four main DBI classes. Three which are each extended by individual database backends:

All classes are virtual: they cannot be instantiated directly and instead must be subclassed.

Further Reading


Please note that the DBI project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.



r-dbi/DBI documentation built on May 6, 2024, 12:03 a.m.