Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sqlite3 with Ruby, is there a way to read each row as a hash instead of array?

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.

like image 811
nonopolarity Avatar asked Oct 21 '25 18:10

nonopolarity


1 Answers

There's results_as_hash setter to get this behavior:

db = SQLite3::Databse.open 'data.db'
db.results_as_hash = true
# ...
like image 126
Marek Lipka Avatar answered Oct 23 '25 07:10

Marek Lipka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!