处理英文文本时,插入到数据库时,英文句子中单引号让我很头疼。脚本如何写才能规避单引号导致的 sql 错误?
我现在非常粗暴的将单引号换为||| , 然后再插入到数据库中。
require "mysql2"
db = Mysql2::Client.new(:host => "localhost", :username => "***", :password => "****", :database => "dictionary")
sentence_en = File.readlines("surgery.esen")
sentence_cn = File.readlines("surgery.csen")
en_count = sentence_en.size
cn_count = sentence_cn.size
reg = %r(')
if en_count != cn_count
p "not correct"
else
en_count.times{|i|
a = sentence_en[i].gsub(reg, "|||")
b = sentence_cn[i].gsub(reg, "|||")
p a,b
db.query("INSERT INTO `pubmed_search_en_cn` (`en`, `cn`, `category`) VALUES ('#{a}', '#{b}', 'surgery')")
}
end
1