简体   繁体   中英

r: escape single quote in a string

I have a string like a <- "abc'def" and I need to paste this into a longer sql string:

 s <- paste0("select * from x where xx ='", a, "'")

But the single quote in the middle makes it fail, I cannot manually replace ' with \\' but need to use a function.

你需要逃离'a适当的到数据库的东西,而不是R.这可能将是它加倍: ''

In many SQL implementations, doubling achieves the escaping you want:

a <- "abc'def"
a <- gsub("'", "''", a)
s <- paste0("select * from x where xx ='", a, "'")

[1] "select * from x where xx ='abc''def'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM