# Require 'postgres'

**URL:** <https://www.ruby-forum.com/t/require-postgres/196577>\
**Category:** Ruby\
**Created:** [January 17, 2008, 10:26pm UTC](https://www.ruby-forum.com/t/require-postgres/196577 "2008-01-17T22:26:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hiddenhippo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/65b543/32.png) [@hiddenhippo](https://www.ruby-forum.com/u/hiddenhippo)\
**Post date:** [January 17, 2008, 10:26pm UTC](https://www.ruby-forum.com/t/require-postgres/196577/1 "2008-01-17T22:26:17Z")

</div>

hi,

I’m trying to write a test application that queries a postgres  
database, which so far I’ve managed to do but in a limited way. I’m  
completely lost how to perform transactions and how to return the  
primary key id for newly inserted rows. hopefully by placing some  
code someone might be able to help,

require ‘postgres’

db = PGconn.connect(‘localhost’,  
5432,’’,’’,‘testdatabase’,‘username’,‘password’)  
results = db.exec(‘select \* from testtable’)

I can then loop on results and display them using puts.

However suppose i wanted to issue the following statement but within a  
transaction? I simply can’t find any documentation anywhere to help  
me

db.exec(‘delete from testtable’)

in addition, suppose i was to insert a row into testtable and want the  
id returned back? i can’t figure that out either.

can anyone help?

---

<div class="post-metadata">

**Author:** ![hiddenhippo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/65b543/32.png) [@hiddenhippo](https://www.ruby-forum.com/u/hiddenhippo)\
**Post date:** [January 18, 2008, 12:30am UTC](https://www.ruby-forum.com/t/require-postgres/196577/2 "2008-01-18T00:30:45Z")

</div>

On Jan 17, 2008 10:25 PM, hiddenhippo [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> db = PGconn.connect(‘localhost’,  
> 5432,‘’,‘’,‘testdatabase’,‘username’,‘password’)  
> results = db.exec(‘select \* from testtable’)
> 
> I can then loop on results and display them using puts.
> 
> However suppose i wanted to issue the following statement but within a  
> transaction? I simply can’t find any documentation anywhere to help  
> me
> 
> db.exec(‘delete from testtable’)

Not entirely sure I understand the problem with that statement.

> in addition, suppose i was to insert a row into testtable and want the  
> id returned back? i can’t figure that out either.

Say testtable contains 2 columns and where is auto  
incremented on insert.

result = db.exec(“INSERT INTO testtable(name) VALUES(‘b’) RETURNING id”)  
q\_id = result[0][0]
