0

我正在使用一个在文件中编写 sql 命令的程序。

该程序是红宝石。我发现它不能正确转义特殊字符。

我找到了进行转义的函数,但它并不完全正确。

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

以前从未使用过 ruby​​,所以有人可以为我提供正确的功能,或者更好地告诉我是否有任何内置方法?

ps 我无法安装任何外部模块

4

1 回答 1

1

假设您只希望此方法将'字符串中出现的 转换s\',这应该有效:

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'

在原始方法中,替换用双引号引起来,因此没有插入反斜杠。

编辑

注意:要替换所有 MySQL 特殊字符,请执行以下操作。我只包含了一些 MySQL 特殊字符——完整列表请查看http://dev.mysql.com/doc/refman/5.0/en/string-literals.html。另请注意,使用自定义转义方法存在安全问题。

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
于 2013-08-15T14:42:24.237 回答