tkluis
4/11/2019 - 9:09 PM

R SQL with Postgresql

# Load libraries 
library(sqldf) 			  # Package that allows SQL programming
library(RPostgreSQL) 	# Package that controls PostgreSQL Database

# SQLDB Options
options(sqldf.RPostgreSQL.user ="postgres", 
        sqldf.RPostgreSQL.password ="<normalpass!1>",
        sqldf.RPostgreSQL.dbname ="rstudiodb",
        sqldf.RPostgreSQL.host ="localhost", 
        sqldf.RPostgreSQL.port =5432)

# SQL
test3 <- sqldf("select * from test_tbl") #drv="SQLite"

# PostgreSQL Connection Info
drv <- dbDriver("PostgreSQL")
            # Simple version (localhost as default)
            # con <- dbConnect(drv) 	
 						# Full version of connection seetting
con <- dbConnect(drv, dbname="rstudiodb",host="localhost",port=5432,user="postgres",password="<normalpass!1>")

# Check if table exists (including schema setup)
dbExistsTable(con, c("temp","test_tbl"))

# Write Table to PostgreSQL Database
dbWriteTable(con, "census_decennial_varlist", value=decennial_varlist,overwrite=TRUE,row.names=FALSE)

# Append Data to PostgreSQL Database Table
dbWriteTable(con, "test_tbl", value=test,append=TRUE, row.names=FALSE)

# Read Data from PostgreSQL Database Table
myTable <- dbReadTable(con, "census_decennial_varlist")

# Close PostgreSQL connection 
dbDisconnect(con)