# NOT RUN {
library(DBI)
db <- RSQLite::datasetsDb()
# Run query to get results as dataframe
dbGetQuery(db, "SELECT * FROM USArrests LIMIT 3")
# Send query to pull requests in batches
rs <- dbSendQuery(db, "SELECT * FROM USArrests")
dbFetch(rs, n = 2)
dbFetch(rs, n = 2)
dbHasCompleted(rs)
dbClearResult(rs)
# Parameterised queries are safest when you accept user input
dbGetQuery(db, "SELECT * FROM USArrests WHERE Murder < ?", list(3))
# Or create and then bind
rs <- dbSendQuery(db, "SELECT * FROM USArrests WHERE Murder < ?")
dbBind(rs, list(3))
dbFetch(rs)
dbClearResult(rs)
# Named parameters are a little more convenient
rs <- dbSendQuery(db, "SELECT * FROM USArrests WHERE Murder < :x")
dbBind(rs, list(x = 3))
dbFetch(rs)
dbClearResult(rs)
dbDisconnect(db)
# Passing multiple values is especially useful for statements
con <- dbConnect(RSQLite::SQLite())
dbWriteTable(con, "test", data.frame(a = 1L, b = 2L))
dbReadTable(con, "test")
dbExecute(con, "INSERT INTO test VALUES (:a, :b)",
params = list(a = 2:4, b = 3:5))
dbReadTable(con, "test")
rs <- dbSendStatement(con, "DELETE FROM test WHERE a = :a AND b = :b")
dbBind(rs, list(a = 3:1, b = 2:4))
dbBind(rs, list(a = 4L, b = 5L))
dbClearResult(rs)
dbReadTable(con, "test")
# Multiple values passed to queries are executed one after another,
# the result appears as one data frame
dbGetQuery(con, "SELECT * FROM TEST WHERE a >= :a", list(a = 0:3))
dbDisconnect(con)
# }
Run the code above in your browser using DataLab