🗄️ R Database Integration – Connect R with MySQL, SQLite, PostgreSQL
🧲 Introduction – Connecting R to Databases
R is not just limited to flat files like CSVs—it also integrates seamlessly with relational databases such as MySQL, PostgreSQL, SQLite, and SQL Server. Using R’s database interface, you can connect, query, and manipulate structured data from live systems directly inside your R script or notebook.
🎯 In this guide, you’ll learn:
- How to connect R to a database
- Use the
DBI
andRMySQL
/RSQLite
packages - Execute SQL queries and retrieve results
- Best practices for closing connections and securing credentials
📦 Required Packages for DB Integration
Database | R Package |
---|---|
SQLite | RSQLite |
MySQL/MariaDB | RMySQL or RMariaDB |
PostgreSQL | RPostgres |
Generic SQL | DBI |
Install core packages:
install.packages("DBI")
install.packages("RSQLite") # For SQLite
# install.packages("RMySQL") # For MySQL (may need system libs)
🧱 1. Connect to a SQLite Database
library(DBI)
con <- dbConnect(RSQLite::SQLite(), dbname = "my_database.sqlite")
🔍 Explanation:
dbConnect()
creates a live connection to the SQLite file.- The connection object
con
is used for running SQL queries.
📤 2. Create a Table and Insert Data
dbWriteTable(con, "students", data.frame(
Name = c("Alice", "Bob"),
Age = c(23, 24)
))
🔍 Explanation:
dbWriteTable()
creates a new table and fills it with data from a data frame.- Table
students
is now part of your SQLite database.
📥 3. Query Data with SQL
result <- dbGetQuery(con, "SELECT * FROM students")
print(result)
🔍 Explanation:
dbGetQuery()
sends an SQL command and returns the result as a data frame.- You can use full SQL syntax:
WHERE
,JOIN
,GROUP BY
, etc.
🔄 4. Insert or Modify Records
dbExecute(con, "INSERT INTO students (Name, Age) VALUES ('Charlie', 22)")
🔍 Explanation:
dbExecute()
is used for write operations (INSERT, UPDATE, DELETE) that don’t return a result.
🔎 5. List and Inspect Tables
dbListTables(con) # Shows all tables
dbListFields(con, "students") # Shows all columns
❌ 6. Close the Database Connection
dbDisconnect(con)
🔍 Explanation:
- Always disconnect after completing database operations to free up resources.
🌐 7. Connecting to MySQL or PostgreSQL (Example)
✅ MySQL Example with RMariaDB
:
# install.packages("RMariaDB")
library(DBI)
con <- dbConnect(RMariaDB::MariaDB(),
user = "root",
password = "your_password",
dbname = "your_database",
host = "localhost")
✅ PostgreSQL Example:
# install.packages("RPostgres")
library(DBI)
con <- dbConnect(RPostgres::Postgres(),
dbname = "your_db",
host = "localhost",
port = 5432,
user = "postgres",
password = "your_pass")
🧠 Security Tips
Tip | Description |
---|---|
Avoid hardcoding credentials | Use readline() or .Renviron for secrets |
Use environment variables | Store credentials in .Renviron file |
Disconnect when done | Prevents connection leaks |
Sys.getenv("DB_PASS")
📌 Summary – Recap & Next Steps
R supports robust integration with SQL databases. With just a few lines, you can query, transform, and load structured data into your analytics workflows.
🔍 Key Takeaways:
- Use
DBI
as a unified interface for various DBMS - SQLite is easiest for local storage
dbConnect()
,dbWriteTable()
, anddbGetQuery()
are key functions- Use
RMariaDB
orRPostgres
for server databases - Secure connections by hiding passwords and disconnecting properly
⚙️ Real-World Relevance:
Used in enterprise systems for dashboarding, ETL processes, production-grade analytics, and combining live DB records with statistical models in R.
❓ FAQs – Database Access in R
❓ What is the best way to store credentials securely in R?
✅ Use .Renviron
to load environment variables:
Sys.getenv("DB_USER")
❓ Can I run JOIN queries in dbGetQuery()
?
✅ Absolutely! Use full SQL syntax:
dbGetQuery(con, "SELECT * FROM table1 JOIN table2 ON ...")
❓ What’s the difference between dbExecute()
and dbGetQuery()
?
✅ dbExecute()
is for writing data; dbGetQuery()
retrieves it.
❓ Can I use R to create and manage SQL tables?
✅ Yes. You can use dbExecute()
to run any valid SQL command, including CREATE
, DROP
, ALTER
.
❓ How do I know which database driver to use?
✅ Use:
RSQLite
for local.sqlite
filesRMariaDB
for MySQL or MariaDBRPostgres
for PostgreSQL
Share Now :