View source: R/connection_helpers.R
| db_with | R Documentation |
Provides automatic connection lifecycle management. The connection is automatically closed when the code block finishes, even if an error occurs. This prevents connection leaks and ensures proper resource cleanup.
db_with(connection_name, code)
connection_name |
Character. Name of the connection in config.yml |
code |
Expression to evaluate with the connection (use |
The result of evaluating code
if (FALSE) {
# Safe - connection auto-closes
users <- db_with("my_db", {
DBI::dbGetQuery(conn, "SELECT * FROM users WHERE active = TRUE")
})
# Multiple operations with same connection
result <- db_with("my_db", {
DBI::dbExecute(conn, "INSERT INTO users (name) VALUES ('Alice')")
DBI::dbGetQuery(conn, "SELECT * FROM users")
})
# Connection closes even on error
tryCatch(
db_with("my_db", {
stop("Something went wrong") # Connection still closes
}),
error = function(e) message(e$message)
)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.