Escaped characters

R

Ruby Tuesday

Hi, I was wondering if there are such a function in Ruby for escaping a
character, e.g:

I'd like to add record to mysql db but it has quote('), double-quote("), and
other escape-able characters.

How do I escape those characters just before pumping it to the database?

Now the strings is clobbered with escape characters, how do I strip it for
searching? Thanks
 
J

Jim Weirich

Ruby Tuesday said:
Hi, I was wondering if there are such a function in Ruby for escaping a
character, e.g:

I'd like to add record to mysql db but it has quote('), double-quote("),
and
other escape-able characters.

How do I escape those characters just before pumping it to the database?

Now the strings is clobbered with escape characters, how do I strip it for
searching? Thanks

Are you using DBI? If so, then form your SQL queries with "?"
placeholders and pass the actual values when the queries are executed.
DBI will handle all the proper quoting and escaping for you.

For example.

db = DBI.connect("DBI:yada:yada", user, pw)
db.do("UPDATE this_table SET a_column = ? WHERE yada = yada",
%{This is is automatically 'quoted' and "escaped" by DBI})

There may be similiar functionality built into the direct DB bindings. If
so, this is generally a better choice than self escaping.

However, DBI does provide an escape unility function you can call
yourself. Given a database handle (such as "db" above) you can use
db.quote(string).
 
R

Robert Klemme

Jim Weirich said:
Ruby Tuesday said:

Are you using DBI? If so, then form your SQL queries with "?"
placeholders and pass the actual values when the queries are executed.
DBI will handle all the proper quoting and escaping for you.

For example.

db = DBI.connect("DBI:yada:yada", user, pw)
db.do("UPDATE this_table SET a_column = ? WHERE yada = yada",
%{This is is automatically 'quoted' and "escaped" by DBI})

There may be similiar functionality built into the direct DB bindings. If
so, this is generally a better choice than self escaping.

If you don't want to use that there's always String#gsub to accomplish
such substitutions - in either direction, e.g.

str.gsub(/(['"])/, '^\\1' )
str.gsub(/^(.)/, '\\1' )

with "^" beeing the escape char in this example.

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top