Learn R Programming

rpg (version 1.6)

prepare: Prepared queries

Description

Prepare and execute queries

Usage

prepare(sql)

Arguments

sql

a valid query string

Value

A function.

The function can take one argument. The values will be used to fill in parameters of the prepared statement. If no argument is passed, the statement will be executed without any parameters.

Details

prepare prepares a statement for later execution. It returns a function that when called executes the prepared statement. Values passed to the returned function will substituted for parameters in the prepared statement. If the number of parameters supplied is a multiple of the number of open parameters in query prepared using prepare, then the prepared query will be executed repeatedly for each successive set of parameters. This repeated execution loop is evaluted in C++ and so is quite fast. The supplied parameter values will be coerced to a matrix of the appropriate dimensions. Values passed to the function will be recycled to match the number of query parameters. The passed parameters will be coerced to character strings.

Examples

Run this code
# NOT RUN {
# try connecting to default database
createdb("rpgtesting")
connect("rpgtesting")
begin()

# write data frame contents
data(mtcars)
write_table(mtcars)

# delete the rows
query("truncate mtcars")
read_table(mtcars)

# use prepare-execute to write rows
pars = paste0("$", 1:11, collapse = ", ")
sql = paste0("INSERT INTO mtcars VALUES (", pars, ")", collapse = " ")
f = prepare(sql)
f(mtcars)
read_table(mtcars, limit = 5)

# cleanup
rollback()
disconnect()
dropdb("rpgtesting")
# }
# NOT RUN {
# }

Run the code above in your browser using DataLab