简体   繁体   English

在Ruby中转义单引号

[英]Escaping single quotes in Ruby

so I'm making a little ruby script to parse a .csv and output a large MySQL query. 因此,我正在制作一些红宝石脚本来解析.csv并输出大型MySQL查询。 The problem is some of the names I'm working with have single quotes, which messes up my SQL... 问题是我使用的某些名称带有单引号,这使我的SQL混乱。

My attempt to gsub the quotes into escape quotes has failed, though I'm not sure why. 我尝试将引号转换为转义引号失败,但是我不确定为什么。 But sure enough when I open my query.txt file a name like D'vinci would be just that, and not D\\'vinci. 但是可以肯定的是,当我打开query.txt文件时,像D'vinci这样的名称就是这样,而不是D \\'vinci。

What am I doing wrong? 我究竟做错了什么?

require 'csv'

filename = ARGV[0]
q = "INSERT INTO `table` (`username`, `password`, `firstname`, `lastname`, `email`) VALUES "

CSV.foreach(filename) do |row|
  last_name, first_name, email, id = row.each {|c| c.gsub "'", "\'"}
  q += "('#{id}', SHA1('password'), '#{first_name}', '#{last_name}', '#{email}'),\n"
end

q += ";"

File.open("query.txt", 'w').write(q)

Do not write your own SQL escaping. 不要编写自己的SQL转义。 Please, always use the methods provided by the appropriate database driver. 始终使用适当的数据库驱动程序提供的方法。

If you're using MySQL, either mysql or the newer mysql2 gem, there's an escape function that should handle this for you. 如果您使用的是MySQL,即mysql或较新的mysql2 gem,则有一个escape函数可以为您处理此问题。

It's not entirely clear why you're writing SQL in the first place when most databases have some kind of import-from-file function. 目前尚不清楚,当大多数数据库具有某种类型的导入文件功能时,为什么要首先编写SQL。 MySQL in particular has LOAD DATA INFILE which can read in many different formats if used correctly. 特别是MySQL,它具有LOAD DATA INFILE ,如果使用正确,它可以以许多不同的格式读取。

each returns the receiver. each返回接收者。 So, your gsub inside that block is doing nothing. 因此,该块内的gsub不会执行任何操作。 Change it to map , and it shall be fine. 将其更改为map ,就可以了。 Or, you can keep the each and use gsub! 或者,您可以保留each并使用gsub! instead. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM