Database connection

There are different ways to open a connection and to get data.

Prepare database with a table

db <- rocker::newDB() # New database handling object
db$setupSQLite(dbname = tempfile()) # Setup SQLite database
db$connect() # Open connection
db$writeTable("mtcars", mtcars) # Create table for testing
db$disconnect() # Close connection

Example 1

Get query with automatic connection / disconnection

output <- db$getQuery("SELECT * FROM mtcars;") # Get query

Example 2

Get query with manual connection / disconnection

db$connect() # Open connection
output1 <- db$getQuery("SELECT * FROM mtcars;") # Get query 1
output2 <- db$getQuery("SELECT * FROM mtcars;", 15) # Get query 2
db$disconnect() # Close connection

Example 3

Function getQuery() is a combination of functions sendQuery(), fetch() and clearResult().

db$connect() # Open connection
db$sendQuery("SELECT * FROM mtcars;") # Send query
output <- db$fetch() # Fetch result
db$clearResult() # Clean up result
db$disconnect() # Close connection

Clean up

db$unloadDriver() # Reset database handling object


Try the rocker package in your browser

Any scripts or data that you put into this service are public.

rocker documentation built on Aug. 21, 2022, 1:06 a.m.