3.8 Import from Databases
If your text data is somewhere in a relational database (like PostgreSQL, MySQL, SQLite, etc.), you can connect directly from R using the DBI (Database Interface) package along with a specific backend package for your database type, such as RPostgres, RMariaDB, RSQLite, odbc. Here, let us try to import a PostgreSQL database file:
library(DBI)
library(RSQLite) # Load the specific backend
connection <- dbConnect(RPostgres::Postgres(), dbname = "your_db", host = "your_host",
port = 5432, user = "your_user", password = "your_password")
print(dbListTables(connection)) # List available tables
query <- "SELECT doc_id, text_content FROM documents WHERE year = 2023;" # Query the database using SQL
results_df <- dbGetQuery(connection, query)
dbDisconnect(connection)