Search code examples
rubypostgresql

Simple example of Postgres query in Ruby


For the life of me I can't find a simple example of just running something like

"SELECT * FROM MyTable"

in Ruby. Everything I'm finding assumes an ORM or Rails. For now, I don't want ORM; I don't want Rails. I'm looking for something standalone that uses the pg gem and executes a simple query.


Solution

  • From the pg gem documentation (http://rubydoc.info/gems/pg/0.10.0/frames)

    require 'pg'
    conn = PGconn.open(:dbname => 'test')
    res  = conn.exec('SELECT 1 AS a, 2 AS b, NULL AS c')
    res.getvalue(0,0) # '1'
    res[0]['b']       # '2'
    res[0]['c']       # nil
    

    My next question would be authentication with a DB that requires a password. Looks like you can send a connection string like this:
    PGconn.connect( "dbname=test password=mypass") or use the constuctor with parameters:
    PGconn.new(host, port, options, tty, dbname, login, password) or use a hash like :password => '...' see here for all available options.