简体   繁体   中英

Escaping ' in Ruby string, without escaping \ for inserting to MySQL

I have a string in Ruby of the form: "Henry's string"

Every gsub and tr I've tried gives me forms like "Henry\\\\'s string" , "Henry\\\\\\\\'s string" , etc.

These are all escaping the backslashes, but leaving me with an unescaped single quote.

I've tried:

  • "Henry's string".gsub("'","\\\\\\\\'") with varying numbers of \\

  • "Henry's string".gsub(/'/) {|x| "\\\\\\\\#{x}"} "Henry's string".gsub(/'/) {|x| "\\\\\\\\#{x}"} again with varying numbers of \\

  • "Henry's string".gsub(/'/) {|x| "\\\\#{x}"}.gsub(/\\\\/) {|x| "#{x}"}

I think I need an odd number of \\ to fully escape the ' (in order to load to MySQL) but I cannot figure out how to get this.

When inserting into a database, like MySQL, it's important to use prepared statements with placeholder values . I've put that in bold because it's extra super important to understand. All it takes is one little slip and you've created a SQL injection hole anyone can exploit and these can be extremely damaging.

Escaping a string might seem superficially simple, but it's not. There's a lot of quirky edge cases you'll need to cover off, the details of which are too complicated to mention here in a short answer.

The simple solution is to not bother escaping at all, instead write queries of this form:

INSERT INTO table_name (column_name) VALUES (?)

Where the ? represents the data you're inserting. You can use these with, for example, the mysql2 driver like this:

stmt = @client.prepare("INSERT INTO table_name (column_name) VALUES (?)")
stmt.execute("Henry's string")

Where that driver will take care of properly encoding the values so you don't have to worry about it.

You can also use something like Sequel or ActiveRecord that simplify things even further.

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