tests/testthat/examples/knitr-examples/115-engine-sql.md

title: "Knit SQL Demo"

library(DBI)
db <- dbConnect(RSQLite::SQLite(), dbname = ":memory:")
DROP TABLE IF EXISTS packages
CREATE TABLE packages (id INTEGER, name TEXT)
INSERT INTO 
  packages 
VALUES 
  (1, 'readr'), 
  (2, 'readxl'), 
  (3, 'haven')
SELECT * FROM packages
Table: 3 records |id |name | |:--|:------| |1 |readr | |2 |readxl | |3 |haven |
packageReadR <- "readr"

Engine can substitute named placeholders in sql that start with ?.

Note that if you don't provide params as option values will be evaluated from environment

SELECT 
  * 
FROM 
  packages
WHERE 
  name = ?packageReadR
readrPackage
##   id  name
## 1  1 readr

To use parameterised queries with native database support provide params in the options of the chunk.

parameters <- list(package = packageReadR)
SELECT 
  * 
FROM
  packages
WHERE 
  name = @package
readrPackage
##   id  name
## 1  1 readr
DROP TABLE IF EXISTS packages
SELECT * FROM packages
## Error: no such table: packages


Try the parsermd package in your browser

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

parsermd documentation built on Aug. 21, 2025, 5:27 p.m.