假设您只希望此方法将'
字符串中出现的 转换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