We use database connections to talk to databases from R. This helps us save, get, and manage data easily.
You want to save your data in a database instead of a file.
You need to get data from a database to analyze it in R.
You want to update or delete data stored in a database.
You want to work with large datasets that don't fit in memory.
You want to share data between different programs using a database.
Syntax
R Programming
library(DBI)
library(RSQLite)
# Connect to a SQLite database file
con <- dbConnect(RSQLite::SQLite(), "path_to_database.sqlite")
# Use the connection to send queries or commands# Disconnect when done
dbDisconnect(con)
Use dbConnect() to open a connection to the database.
Always close the connection with dbDisconnect() to free resources.
Examples
This creates a temporary database stored in memory. It disappears when you disconnect.
R Programming
library(DBI)
library(RSQLite)
# Connect to a new in-memory database
con <- dbConnect(RSQLite::SQLite(), ":memory:")
This connects to a database saved in the file my_data.sqlite. Data stays after R closes.
R Programming
library(DBI)
library(RSQLite)
# Connect to a file-based database
con <- dbConnect(RSQLite::SQLite(), "my_data.sqlite")
Always disconnect when you finish working with the database to avoid problems.
R Programming
dbDisconnect(con)
Sample Program
This program creates a small database in memory, adds a table and data, then reads and prints the data.
R Programming
library(DBI)
library(RSQLite)
# Connect to an in-memory SQLite database
con <- dbConnect(RSQLite::SQLite(), ":memory:")
# Create a table named 'people'
dbExecute(con, "CREATE TABLE people (id INTEGER, name TEXT)")
# Insert some data
dbExecute(con, "INSERT INTO people (id, name) VALUES (1, 'Alice'), (2, 'Bob')")
# Query the data
result <- dbGetQuery(con, "SELECT * FROM people")
# Print the resultprint(result)
# Disconnect
dbDisconnect(con)
OutputSuccess
Important Notes
Use dbExecute() for commands that change data or structure (like CREATE or INSERT).
Use dbGetQuery() to run SELECT queries and get results as data frames.
SQLite databases are simple and good for learning or small projects.
Summary
Database connections let R talk to databases to save and get data.
Use dbConnect() to open and dbDisconnect() to close connections.
Use dbExecute() for changes and dbGetQuery() to read data.
Practice
(1/5)
1. What is the main purpose of dbConnect() in R when working with databases?
easy
A. To run a SQL query and get results
B. To close an open database connection
C. To open a connection to a database
D. To create a new table in the database
Solution
Step 1: Understand the role of dbConnect()
dbConnect() is used to start a connection between R and a database so they can communicate.
Step 2: Differentiate from other functions
dbDisconnect() closes connections, dbGetQuery() runs queries, and dbExecute() changes data. Only dbConnect() opens the connection.
2. Which of the following is the correct syntax to connect to an SQLite database file named mydata.sqlite using DBI in R?
easy
A. dbConnect(SQLite::RSQLite(), file = "mydata.sqlite")
B. dbConnect(SQLite, "mydata.sqlite")
C. dbConnect(RSQLite, dbname = "mydata.sqlite")
D. dbConnect(RSQLite::SQLite(), dbname = "mydata.sqlite")
Solution
Step 1: Identify correct function usage
The correct way is to call dbConnect() with the driver RSQLite::SQLite() and specify the database file with dbname.
Step 2: Check each option
dbConnect(RSQLite::SQLite(), dbname = "mydata.sqlite") uses the correct driver and argument name. Options B, C, and D misuse the driver or argument names.
Final Answer:
dbConnect(RSQLite::SQLite(), dbname = "mydata.sqlite") -> Option D
Hint: Use RSQLite::SQLite() and dbname for file [OK]
Common Mistakes:
Using wrong driver syntax
Using 'file' instead of 'dbname'
Omitting the namespace RSQLite::
3. What will be the output of the following R code?
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbExecute(con, "CREATE TABLE test (id INTEGER, name TEXT)")
dbExecute(con, "INSERT INTO test VALUES (1, 'Alice'), (2, 'Bob')")
res <- dbGetQuery(con, "SELECT name FROM test WHERE id = 2")
print(res)
dbDisconnect(con)
medium
A. name
1 Bob
B. id name
1 2 Bob
C. Error: no such table: test
D. NULL
Solution
Step 1: Understand the code flow
The code creates an in-memory SQLite database, makes a table 'test', inserts two rows, then queries the name where id=2.
Step 2: Predict the query result
The query selects the 'name' column for id=2, which is 'Bob'. The printed result is a data frame with one row and one column 'name' containing 'Bob'.
Final Answer:
name
1 Bob -> Option A
Quick Check:
Query returns name 'Bob' for id=2 [OK]
Hint: SELECT returns matching rows as data frame [OK]
Common Mistakes:
Expecting full row instead of selected column
Confusing dbExecute with dbGetQuery output
Forgetting to disconnect connection
4. Identify the error in the following R code snippet that tries to connect to an SQLite database and run a query:
library(DBI)
con <- dbConnect(RSQLite::SQLite(), "mydb.sqlite")
result <- dbGetQuery(con, "SELECT * FROM users")
dbDisconnect(con)
medium
A. dbDisconnect() should be called before dbGetQuery()
B. The database file name should be passed as dbname argument, not directly
C. dbGetQuery() cannot be used with SQLite
D. The library DBI is not needed for SQLite connections
Solution
Step 1: Check dbConnect() usage
The SQLite file name must be passed as dbname = "mydb.sqlite", not as a positional argument.
Step 2: Verify other function calls
Calling dbGetQuery() before dbDisconnect() is correct. dbGetQuery() works with SQLite. The DBI library is required.
Final Answer:
The database file name should be passed as dbname argument, not directly -> Option B
Quick Check:
Use dbname= for file in dbConnect() [OK]
Hint: Always name dbname argument in dbConnect() [OK]
Common Mistakes:
Passing file name without dbname=
Disconnecting before query
Thinking DBI is unnecessary
5. You want to create a new SQLite database in R, add a table named employees with columns id (integer) and name (text), insert three employees, and then retrieve all names. Which sequence of commands correctly achieves this?
hard
A. con <- dbConnect(RSQLite::SQLite(), dbname = "company.sqlite")
dbExecute(con, "CREATE TABLE employees (id INTEGER, name TEXT)")
dbExecute(con, "INSERT INTO employees VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara')")
names <- dbGetQuery(con, "SELECT name FROM employees")
dbDisconnect(con)
print(names)
B. con <- dbConnect(RSQLite::SQLite(), "company.sqlite")
dbExecute(con, "CREATE employees (id INTEGER, name TEXT)")
dbExecute(con, "INSERT INTO employees VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara')")
names <- dbGetQuery(con, "SELECT name FROM employees")
dbDisconnect(con)
print(names)
C. con <- dbConnect(RSQLite::SQLite(), dbname = "company.sqlite")
dbExecute(con, "CREATE TABLE employees (id TEXT, name INTEGER)")
dbExecute(con, "INSERT INTO employees VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara')")
names <- dbGetQuery(con, "SELECT id FROM employees")
dbDisconnect(con)
print(names)
D. con <- dbConnect(RSQLite::SQLite(), dbname = "company.sqlite")
dbExecute(con, "CREATE TABLE employees (id INTEGER, name TEXT)")
dbExecute(con, "INSERT INTO employees VALUES (1, 'Anna')")
dbExecute(con, "INSERT INTO employees VALUES (2, 'Ben')")
dbExecute(con, "INSERT INTO employees VALUES (3, 'Cara')")
names <- dbGetQuery(con, "SELECT id FROM employees")
dbDisconnect(con)
print(names)
Solution
Step 1: Identify correct sequence
Use dbConnect(RSQLite::SQLite(), dbname = "company.sqlite"), CREATE TABLE employees (id INTEGER, name TEXT), multi-row INSERT INTO employees VALUES (1, 'Anna'), (2, 'Ben'), (3, 'Cara'), SELECT name FROM employees.
Step 2: Eliminate distractors
B: No dbname=, missing TABLE. C: Wrong types (name INTEGER fails insert), selects id. D: Selects id instead of name.
Final Answer:
dbConnect(RSQLite::SQLite(), dbname = "company.sqlite"), correct CREATE TABLE, multi-row INSERT, SELECT name -> Option A
Quick Check:
dbname=, id INTEGER name TEXT, INSERT 3 rows, SELECT name [OK]
Hint: Insert multiple rows in one dbExecute for efficiency [OK]
Common Mistakes:
Passing file name without dbname=
Wrong SQL syntax for CREATE TABLE
Mixing column types (id TEXT instead of INTEGER)
Selecting id instead of name
Forgetting to disconnect
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.