Integration with Databases using DBI and RMySQL

R can connect to databases to perform data analysis on large datasets. Here’s how to connect to a MySQL database.

Step 1: Install and Load Required Packages

rCopy codeinstall.packages("DBI")
install.packages("RMySQL")
library(DBI)
library(RMySQL)

Step 2: Connect to the Database

rCopy code# Connect to the MySQL database
con <- dbConnect(RMySQL::MySQL(), 
                 dbname = "your_database_name",
                 host = "your_host",
                 user = "your_username",
                 password = "your_password")

Step 3: Query Data

rCopy code# Query data from a table
data_db <- dbGetQuery(con, "SELECT * FROM your_table_name LIMIT 100")

# View the queried data
head(data_db)

Step 4: Disconnect from the Database

rCopy code# Disconnect from the database
dbDisconnect(con)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *