require 'postgres'

H

hiddenhippo

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?
 
J

J-H Johansen

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')

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 <id> and <name> where <id> is auto
incremented on insert.

result = db.exec("INSERT INTO testtable(name) VALUES('b') RETURNING id")
q_id = result[0][0]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top