Escaping a single quotation within SQL query

后端 未结 1 1222
慢半拍i
慢半拍i 2020-12-05 05:55

I have a table companies, which has two columns named name and address. By running the following code, new data are inserted into the

相关标签:
1条回答
  • 2020-12-05 06:11

    If you must do it this way then use the quote method on the connection object:

    quote(value, column = nil)
    Quotes the column value to help prevent SQL injection attacks.

    So something like this:

    my_name    = ActiveRecord::Base.connection.quote("John O'Neil")
    my_address = ActiveRecord::Base.connection.quote("R'lyeh")
    
    query = "INSERT INTO companies (name,address) VALUES (#{my_name}, #{my_address})"
    
    ActiveRecord::Base.connection.execute(query);
    

    Never ever try to handle your own quoting. And don't try to use double quotes for quoting an SQL string literal, that's what single quotes are for; double quotes are for quoting identifiers (such as table and column names) in most databases but MySQL uses backticks for that.

    0 讨论(0)
提交回复
热议问题