1

You know certainly about .mode column & headers on, to show datas of a sqlite database. But how to obtain the same result wth in Ruby script?

For example, to add it to my own script:

begin
    require 'sqlite3'
    db = SQLite3::Database.open('test_albums.db')
    db.execute("select * from albums where ecoute = 2") do |result|
        puts result.join(' - ')
    end
end

Very thanks!

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
  • of course, to replace line #5 (puts . . .) – peter pinkness May 15 '17 at 15:52
  • 1
    I'd recommend looking into using [Sequel](http://sequel.jeremyevans.net). It'll make your life easier by allowing you to start with SQLite, then easily switch to a more powerful DBM when you are ready. Also, read "[ask]" and "[mcve]" and "[How much research effort is expected of Stack Overflow users?](http://meta.stackoverflow.com/questions/261592)" – the Tin Man May 16 '17 at 00:53
  • Hi, thanks for advices - I'll see that about Sequel... – peter pinkness May 16 '17 at 03:54

1 Answers1

1

You need to get the table info using pragma table_info(), e.g.:

begin
  require 'sqlite3'
  db = SQLite3::Database.open('test_albums.db')

  columns = db.execute("pragma table_info(albums)")
  puts (columns.map { |c| c[1] }).join(' - ')

  db.execute("select * from albums  where ecoute = 2") do |result|
    puts result.join(' - ')
  end
end
varro
  • 2,382
  • 2
  • 16
  • 24