Skip to content

Instantly share code, notes, and snippets.

@vanderhoop
Last active January 27, 2016 15:46
Show Gist options
  • Select an option

  • Save vanderhoop/be32262c0cf1bf8ac29d to your computer and use it in GitHub Desktop.

Select an option

Save vanderhoop/be32262c0cf1bf8ac29d to your computer and use it in GitHub Desktop.

The PG Gem Cheatsheet

To use the pg gem, you first have to require it.

require 'pg'

Great, now to open a line of communication between your Ruby program and your postgres database, you will use the PG object's ::connect method, passing it a hash with key-value pairs for :host and :dbname).

# stores the resulting connection in a variable so that you can use it to communicate with the db.
pg_connection = PG.connect({ :dbname => 'WHATEVER_YOU_NAMED_YOUR_DB', :host => 'localhost' })

# the exec method will execute whatever sql string is passed to it. Try it out.
results = pg_connection.exec("SELECT * FROM some_table_name;")

# the results variable now holds sweet, sweet database entries, and it includes the enumerable module, so you can iterate through the entries with a number of sweet methods.
results.each { |row| puts row }

Additional Resources

PG Gem Documentation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment