我已经尝试过多次使用R中的RPostgreSQL
包运行参数化的SQL语句。我能够使用位置参数来运行参数化的语句,但是,我对命名参数没有好运。在RPostgreSQL中这可能吗?
library(DBI)
# Connect to Database
con = dbConnect(...) # connection secrets hidden in .Rprofile
create_products_sql =
"CREATE TABLE products (product_no SERIAL PRIMARY KEY, name text, price numeric);"
dbExecute(con, create_products_sql)
products = data.frame(product_no = 1:4,
name=c("Laptop", "Milk", "Bread", "Couch"),
price=c(699.99, 2.49, 3.49, 299.99)
)
dbWriteTable(con, "products", products, append=T, row.names=F)
# Positional Arguments
sql = "INSERT INTO products (product_no, name, price) VALUES ($1, $2, $3);"
dbExecute(con, sql, params=list(5, "Eggs", 1.99))
# Named Arguments
sql = "INSERT INTO products (product_no, name, price) VALUES ($product_no, '$name', $price);"
dbExecute(new_con, sql, params=list(product_no=6, name="TV", price=300))
dbDisconnect(con)
我尝试了参数化SQL语句的几种变体,包括
sql = "INSERT INTO products (product_no, name, price) VALUES ($product_no, '$name', $price);"
和
sql = "INSERT INTO products (product_no, name, price) VALUES (:product_no, ':name', :price);"
无济于事。是否可以在RPostgreSQL
中执行此操作,还是需要使用RPostgres
?