[英]Write to a file mysql commands with ruby
I am using a program that write sql commands in a file. 我正在使用在文件中写入sql命令的程序。
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 PS我不能安装任何外部模块
Assuming you just want this method to convert occurrences of '
in the string s
to \\'
, this should work: 假设您只希望此方法将字符串
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'
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. 注意:要替换所有MySQL特殊字符,请执行以下操作。 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 .
我只包含了几个MySQL特殊字符-有关完整列表,请访问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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.