Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 408
Larsenal Avatar asked Jan 13 '11 17:01

Larsenal


People also ask

How do I run a query in PostgreSQL?

To do this in PL/pgSQL, use the PERFORM statement: PERFORM query ; This executes query and discards the result. Write the query the same way you would write an SQL SELECT command, but replace the initial keyword SELECT with PERFORM .

What is a PostgreSQL query?

Advertisements. PostgreSQL SELECT statement is used to fetch the data from a database table, which returns data in the form of result table. These result tables are called result-sets.

Which query language is used in PostgreSQL?

SQL is the language PostgreSQL and most other relational databases use as query language. It's portable and easy to learn.


1 Answers

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.

like image 180
justinxreese Avatar answered Oct 08 '22 23:10

justinxreese