我有以下字符串数组:
array = [id, message, date, length]
示例:
array = ["1", "test's message", "2016-01-01", "15"]
我想将它合并为一个字符串。我将使用该字符串在DB中插入数据:
ActiveRecord::Base.connection.execute
我做了:
result = "(#{array[0}', '#{array[1]}', '#{array[2]}', '#{array[3]}')"
message
包含特殊字符'
(ASCII代码039)。这导致SQL异常。如何构造包含result
字符的'
字符串?
编辑:
要将数据放入BD我使用:
conn = ActiveRecord::Base.connection
sql = "INSERT INTO table_name (`id`, `message`, `date`, `length`) VALUES #{result}"
conn.execute sql
编辑:
我使用AR方法解决了这个问题:
ActiveRecord::Base.connection.quote(message)
答案 0 :(得分:2)
答案在这里:
How to insert a value that contains an apostrophe (single quote)?
你基本上加倍了撇号:"test''s message"
答案 1 :(得分:1)
您可以使用此代码生成结果。
array = ["1", "test's message", "2016-01-01", "15"]
result = "(#{array.map{|s| s.gsub!("'", "''"); "'#{s}'"}.join(",")})"
# => => "('1','test''s message','2016-01-01','15')"
答案 2 :(得分:0)
你需要像这样转义特殊字符
array = ["1", "test''s message", "2016-01-01", "15"]
答案 3 :(得分:-2)
使用Array#join
Doc Link
arr = [id, message, data, length]
join_result = arr.join(',')