Search code examples
rrmysql

Backslash problems in R query string


So, "\", is crushing my soul. I'm working on a query for RMySQL that requires some strange string escapes and I can't seem to find the right invocation of paste.

query <- 'CALL `storedprocX`(1, 30, "\'xyz-f43\', \'1002\'")'

My attempts so far have been close but I can't seem to get the literal backslashes in the right spot.

ids <- c("xyz-f43","1002")
x <- 1
y <- 30

paste0('CALL `storedprocX`(',x,',',y,paste0(" \\'",ids,"\\'",collapse = ","),')')

Anyone have experience with this?


Solution

  • I am not familiar with RMySQL but isn't the SQL engine taking care of escaping?

    > esc.ids = paste(sprintf("\\'%s\\'", ids), collapse = ", ")
    > esc.ids = paste0("\"", esc.ids, "\"", collapse = "")
    > my.q = paste0("'CALL `storedprocX`(1, 30, ", esc.ids, ")'", collapse = "")
    > cat(my.q)
    'CALL `storedprocX`(1, 30, "\'xyz-f43\', \'1002\'")'
    > nchar(my.q)
    [1] 52
    

    Would SQL not do the same cat does here?