4

I am using sqlite3 as follows:

db = SQLite3::Database.open "data.db"

stm = db.prepare "SELECT * FROM COMPANIES"
rs = stm.execute

while (row = rs.next) do
    name = row[1]

that is, the row is an array instead of a hash. Is there a way to read it as a hash, so that

row[:name]
row[:address]

is the data. That's because in the future, if the table has a different order of columns, row[3] may become row[5], so row[:address] is much more definite.

1
  • 2
    Rather than use the SQLite gem, I'd recommend one of the ORMs that help insulate you from a DBM-specific language. SQLite is nice, but if your DB needs grow having to rewrite all your calls for a different DBM is a major pain. I like Sequel because it's very agnostic and very capable. sequel.jeremyevans.net/rdoc/files/doc/cheat_sheet_rdoc.html is a good overview. Commented Dec 9, 2019 at 7:33

1 Answer 1

5

There's results_as_hash setter to get this behavior:

db = SQLite3::Databse.open 'data.db'
db.results_as_hash = true
# ...
Sign up to request clarification or add additional context in comments.

1 Comment

works great. I suppose it has to be row["NAME"] and can't be made to row[:NAME]?

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.