我正在尝试使用占位符和RMySQL查询。例如,我在MySQL中有这个表,
id name birth color foods cats
1 Sybil 1970-04-13 black lutefisk,fadge,pizza 3
2 Nancy 1969-09-30 white burrito,curry,eggroll 4
3 Ralph 1973-11-02 red eggroll,pizza 4
我想在此表中插入一条记录,从阅读dbBind的文档开始,我想我可以使用下面的代码进行操作,
library(RMySQL)
con <- dbConnect(MySQL(), user = "cbuser", password = "cbpass", dbname =
"cookbook", host = "localhost")
sql <- "INSERT INTO profile (name,birth,color,foods,cats)
VALUES(?,?,?,?,?)"
values <- list("De'Mont", "1973-01-12", NULL, "eggroll", 4)
rs <- dbSendStatement(con, sql)
dbBind(rs, values)
rows <- dbGetRowsAffected(rs)
dbClearResult(rs)
但是当我运行这个时,我得到以下错误,
Error in .local(conn, statement, ...) :
could not run statement: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to
use near '?,?,?,?,?)' at line 2
如果我避开占位符,我可以成功插入记录,例如下面的
sql <- "INSERT INTO profile (name,birth,color,foods,cats)
VALUES('De\\'Mont','1973-01-12',NULL,'eggroll',4)"
rs <- dbSendStatement(con, sql)
但我的理解是使用占位符可能是有利的(例如,自动处理转义字符)所以我想了解它是如何工作的。