RSQLite
library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
df <- data.frame(a=1:5, b=sprintf('"%s"', letters[1:5]), stringsAsFactors=F)
df
# a b
# 1 1 "a"
# 2 2 "b"
# 3 3 "c"
# 4 4 "d"
# 5 5 "e"
dbWriteTable(con, "tbl", df)
# [1] TRUE
dbGetQuery(con, 'select * from tbl')
# a b
# 1 1 "a"
# 2 2 "b"
# 3 3 "c"
# 4 4 "d"
# 5 5 "e"
dbGetQuery(con, 'select * from tbl where b="a"')
# [1] a b
# <0 rows> (or 0-length row.names)
无论如何,使用参数化查询通常是一件好事,所以两鸟一石,可以这么说:
dbGetQuery(con, 'select * from tbl where b=:x', params=list(x='"a"'))
# a b
# 1 1 "a"
dbGetQuery(con, 'select * from tbl where b in (:x)', params=list(x=c('"a"','"c"')))
# a b
# 1 1 "a"
# 2 3 "c"
RMySQL
(我手边没有 mysql 的实例,所以这是一个猜测。)
使用@x
代替:x
:
dbGetQuery(con, 'select * from tbl where b=@x', params=list(x='"a"'))