1

I have the following array of strings:

array = [id, message, date, length]

Example:

array = ["1", "test's message", "2016-01-01", "15"] 

I want to merge it into one string. I will use that string to insert data in DB using:

ActiveRecord::Base.connection.execute

I did:

result = "(#{array[0}', '#{array[1]}', '#{array[2]}', '#{array[3]}')"

message contains special characters ' (ASCII code 039). This results in SQL exception. How can I construct a result string that includes the ' character?

EDIT:

To put data in BD I use:

conn = ActiveRecord::Base.connection
sql = "INSERT INTO table_name (`id`, `message`, `date`, `length`) VALUES #{result}"
  conn.execute sql

EDIT:

I fixed this using AR method:

ActiveRecord::Base.connection.quote(message)
7
  • 2
    You are doing it wrong. There is 2016 around an no one sane developer would construct SQL by joining strings. Commented Jul 18, 2016 at 7:18
  • At which point is the exception raised? During loading the file? During generation of the string? During SQL query? Commented Jul 18, 2016 at 7:19
  • You are doing it wrong. There is 2016 around an no one sane developer would construct SQL by joining strings. Why? I need performance. I want to put data in DB using raw SQL. I don't need AR because I have validated data and I am not scared about Dependency injection because it is simple backgroud job. Tell my why. I have huge amount of data and using plain sql increases inserting 20x Commented Jul 18, 2016 at 7:20
  • At which point is the exception raised? During loading the file? During generation of the string? During SQL query? exception is rised because I have ' char in message string. This is why I am asking how merge strings with special characters. You don't need exception message. Commented Jul 18, 2016 at 7:23
  • Cannot be reproduced. The error is not raised because there is a ' in the message string. Commented Jul 18, 2016 at 7:24

4 Answers 4

2

answer is here:

How to insert a value that contains an apostrophe (single quote)?

You basically double up the apostrophe: "test''s message"

Sign up to request clarification or add additional context in comments.

Comments

1

You can use this code for generate result.

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')"

Comments

0

You need to escape the special character like this

array = ["1", "test''s message", "2016-01-01", "15"] 

Comments

-2

Use Array#join Doc Link

arr = [id, message, data, length]
join_result = arr.join(',')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.