Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Last active November 8, 2018 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarrettmeyer/27fc299099376886d5b650c018d96c74 to your computer and use it in GitHub Desktop.
Save jarrettmeyer/27fc299099376886d5b650c018d96c74 to your computer and use it in GitHub Desktop.
# Import libraries. You don't really need tidyverse, I just like working with tibbles.
library(RPostgreSQL)
library(tidyverse)
record_count = 1000
min_date = "2015-01-01"
max_date = "2018-12-31"
actions = c("Button click", "Fetch data", "Page load", "Refresh")
users = c("Allen", "Brian", "Charlie", "Dave", "Evan")
# Create the SQL statement.
sql_statement = paste("INSERT INTO \"actions\"",
"(\"action\", \"user\", \"timestamp\")",
"VALUES",
"($1, $2, $3)")
print(paste("SQL Statement:", sql_statement))
# Connect to the database.
driver = dbDriver("PostgreSQL")
connection = dbConnect(driver,
host = "XXX.XXX.XXX.XXX",
port = 5432,
user = "XXXXXXXX",
password = "XXXXXXXXXXXXXXXXXXXXXX"
dbname = "XXXXXXXXXXXXX")
dates = seq(from = as.POSIXct(as.Date(min_date)),
to = as.POSIXct(as.Date(max_date)),
by = "min")
data = tibble(action = sample(actions, record_count, repalce = TRUE),
user = sample(users, record_count, replace = TRUE),
timestamp = sample(dates, record_count, replace = TRUE))
for (index in seq_len(record_count)) {
row = data[index,]
dbExecute(connection, sql_statement, row)
}
print(paste("Inserted", record_count, "rows."))
# Clean up after yourself and disconnect from the database.
dbDisconnect(connection)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment