简体   繁体   中英

Write to a file mysql commands with ruby

I am using a program that write sql commands in a file.

The program is in ruby. I found out that it does not escape properly special chars.

I found the function that does the escaping but its not completely correct.

def escape_for_sql(s)
    s=s.to_s
    if s.nil?
    "''"
    else
        "'"+ s.gsub("'","\'")+"'"
    end
end

Never used ruby before, so does someone can provide me a correct function or even better to tell me if there is any built in method?

ps I cannot install any external module

Assuming you just want this method to convert occurrences of ' in the string s to \\' , this should work:

def escape_for_sql(s)
  s=s.to_s
  if s.nil?
    "''"
  else
    "'" + s.gsub("'") { %q{\'} } + "'"
  end
end

puts escape_for_sql "hello, this 'is' a string"
# => 'hello, this \'is\' a string'

In the original method, the replacement was wrapped in double quotes, so the backslash wasn't getting inserted.

EDIT

Note: to replace all MySQL special characters, do something like below. I've only included a few of the MySQL special characters--for a full list check out http://dev.mysql.com/doc/refman/5.0/en/string-literals.html . Also note that there are security concerns with using a custom escaping method.

def escape_for_sql(s)
  s=s.to_s
  if s.nil?
    "''"
  else
    literals = %w{ % ' " \r \n }
    literals.each do |x|
      s.gsub!(/#{x}/) { '\\' + x }
    end
    "'" + s + "'"
  end
end

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