Skip to content

Instantly share code, notes, and snippets.

@cwgem
Created July 31, 2011 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwgem/1117045 to your computer and use it in GitHub Desktop.
Save cwgem/1117045 to your computer and use it in GitHub Desktop.
Postgres Connection and Query Sample
#! /usr/bin/env ruby
#
# original file src/test/examples/testlibpq.c
#
require 'pg'
def main
begin
conn = PGconn.connect(:dbname => 'template1', :port => 5432, :password => 'somestrongpassword')
if $DEBUG
fd = open("/tmp/trace.out","w")
conn.trace(fd)
end
res = conn.exec("BEGIN")
res.clear
res = conn.exec("DECLARE myportal CURSOR FOR select * from pg_database")
res.clear
res = conn.exec("FETCH ALL in myportal")
if (res.result_status != PGresult::PGRES_TUPLES_OK)
raise PGerror,"FETCH ALL command didn't return tuples properly\n"
end
for fld in res.fields
printf("%-15s",fld)
end
printf("\n\n")
res.values.each do |tupl|
tupl.each do |fld|
printf("%-15s",fld)
end
printf("\n")
end
res = conn.exec("CLOSE myportal")
res = conn.exec("END")
res.clear
conn.close
if $DEBUG
fl.close
end
rescue PGError
if (conn.status == PGconn::CONNECTION_BAD)
printf(STDERR, "We have lost the connection to the backend, so ")
printf(STDERR, "further processing is impossible. ")
printf(STDERR, "Terminating.\n")
else
printf(STDERR, conn.error)
end
exit(1)
end
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment