简体   繁体   English

如何从Ruby on Rails转义MYSQL查询?

[英]How to escape for MYSQL queries from Ruby on Rails?

When searching the MYSQL database for a Rails 2.3.14 app, I need to escape the search string appropriately so I can search for strings containing single-quotes (apostrophes). 在MYSQL数据库中搜索Rails 2.3.14应用程序时,我需要适当地转义搜索字符串,以便搜索包含单引号(撇号)的字符串。 What's the best way to do this? 最好的方法是什么? I'm using the mysql gem, in case that matters. 我正在使用mysql gem,以防万一。

When using the mysql gem, you gain the method Mysql.escape_string() . 使用mysql gem时,您获得了Mysql.escape_string()方法。 Use as follows: 使用方法如下:

search_terms = Mysql.escape_string("it's working!")
conditions = [ "table1.name LIKE '%#{search_terms}%'" ]
# use conditions for MYSQL query as appropriate

Rails quotes strings as follows: Rails 引用字符串如下:

# Quotes a string, escaping any ' (single quote) and \ (backslash) characters.
def quote_string(s)
  s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode)
end

You can use ActiveRecord's quote method (eg ActiveRecord::Base.connection.quote("string with ' apostrophe") ), but ActiveRecord's query methods already escape your SQL for you. 您可以使用ActiveRecord的quote方法(例如ActiveRecord::Base.connection.quote("string with ' apostrophe") ),但ActiveRecord的查询方法已经为您转义了SQL。 For example: 例如:

a = "string with ' apostrophe"
ModelName.where("field1 = ?", a)

will change "string with ' apostrophe" to "string with '' apostrophe" 将“带'撇号'的字符串更改为”字符串带''撇号“

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

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