Skip to content

Searching for a string in RSQLite

5 messages · Duncan Murdoch, David James, Dr Mike Waters +1 more

#
I'd like to search for a particular string in an SQLite database using
RSQLite, but I'm running into problems constructing the query
properly, because of embedded quotes and parens in the string.

Is there a function that escapes these for me, or some other fixup
that would let me do the queries below?  In the real situation I don't
have control over what strings get searched for.

Example based on ?SQLite:
[1] TRUE
# this works fine:
row_names Murder Assault UrbanPop Rape
1   Wyoming    6.8     161       60 15.6

# Buf if the search string contains characters that SQL interprets, I
# get an error
Error in sqliteExecStatement(con, statement) : 
        RS-DBI driver: (error in statement: near "(": syntax error)

Duncan Murdoch
#
Single quotes in a string are escaped by putting two single quotes in
a row.  E.g., 

   state <- "mess: '' ("

Regards,

--
David
Duncan Murdoch wrote:
#
The normal character for escaping the next character to prevent it being
interpreted in SQL (including SQLite) is the backslash (i.e. \). Unless, of
course, I'm not understanding the precise nature of your request.

Regards

Mike
#
You may find dQuote() and sQuote() to be helpful, but a better
solution might be to ask the developers of the RSQLite package to add
R functions that call the SQLite api functions sqlite_exec_printf()
and sqlite_get_table_printf() which automatically escape single quotes
(among other things, http://www.sqlite.org/c_interface.html)

Hadley
#
Ooops, dQuote() and sQuote() won't be of much use as they escape
quotes with quotes.

A regular expression should do the trick: gsub("'", "\\\\'", "Hi
y'all").  (Note that this looks like it has too many backslashes, but
this is just the way R prints escaped strings, use str() to see the
unescaped string)

Hadley