New run() method to simplify things in pg8000

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

New run() method to simplify things in pg8000

Tony Locke
Hi all, pg8000 is a pure-Python driver for Postgres
https://github.com/tlocke/pg8000 and in the latest version of pg8000
I've added a run() method to the connection that lets you run SQL
statements without needing a cursor. The idea is to make things a bit
simpler for people. There are a few other differences too. The run()
method always uses the 'named' parameter style, and the parameters are
always provided as keyword arguments. Here's an example:

>>> import pg8000
>>>
>>> # Connect to the database with user name postgres
>>>
>>> con = pg8000.connect("postgres", password="C.P.Snow")
>>>
>>> # Create a temporary table
>>>
>>> con.run("CREATE TEMPORARY TABLE book (id SERIAL, title TEXT)")
()
>>>
>>> # Populate the table
>>>
>>> for title in ("Ender's Game", "The Magus"):
...     con.run("INSERT INTO book (title) VALUES (:title)", title=title)
()
()
>>>
>>> # Print all the rows in the table
>>>
>>> for row in con.run("SELECT * FROM book WHERE id > :min_id", min_id=0):
...     print(row)
[1, "Ender's Game"]
[2, 'The Magus']
>>>
>>> # Commit the transaction
>>>
>>> con.commit()

I'd be interested in any thoughts / feedback if you have any.

Thanks,

Tony.