I need to insert a data frame into a SQL database. I've build the script (using loops, str_c, RODBC) to transform my data frame into a SQL Insert command, but I've run into the problem with a single "'" breaking the SQL.
Here is an example of the problem:
The Data Frame looks like this:
pk b
1 o'keefe
The desired SQL output is: INSERT INTO table (pk, b) (1, 'o\'keefe')
gsub("'", "\'", str_replace_na(df$b[1], ""))
[1] "o'keefe"
gsub("'", "\\\\'", str_replace_na(df$b[1], ""))
[1] "o\\'keefe"
I've tried str_replace
, str_replace_all
, gsub w/ fixed = TRUE
and perl = TRUE
and I get the same result.
I am aware of the comment on How to give Backslash as replacement in R string replace, which states cat()
shows the slash. But this doesn't carry over to my data frame or SQL query.
Any help on this problem would be greatly appreciated!
Additional note, I am aware the R prints a double backslash as referenced http://r.789695.n4.nabble.com/gsub-replacing-double-backslashes-with-single-backslash-td4453328.html and R: How to replace space (' ') in string with a *single* backslash and space ('\ ') even though only one slash really exists. However, my SQL statement still won't work when zero or two backslashes are present.