I had to write a quick feed parser using psycopg before and was wondering why stuff didn't save.
Turns out I was missing a very important line at the end... connection.commit() !
A quick example below shows how to use psycopg.
01.
import
psycopg2
02.
03.
class
SaveStuff():
04.
connection
=
None
05.
cursor
=
None
06.
07.
def
__init__(
self
):
08.
# Connect to an existing database
09.
self
.connection
=
psycopg2.connect(
"dbname=yourdbname user=username host=twigstechtips.blogspot.com"
)
10.
self
.cursor
=
self
.connection.cursor()
11.
12.
def
__del__(
self
):
13.
if
self
.cursor
is
not
None
:
14.
self
.cursor.close();
15.
16.
if
self
.connection
is
not
None
:
17.
self
.connection.close();
18.
19.
def
save(
self
, items):
20.
if
self
.cursor
is
None
:
21.
raise
Exception(
"Invalid connection to database."
)
22.
23.
# Delete existing
24.
self
.cursor.execute(
"DELETE FROM table_name"
)
25.
26.
# Fill in the new values
27.
for
item
in
items:
28.
sql
=
"INSERT INTO table_name (id, name, weight) VALUES (%s, %s, %s)"
29.
self
.cursor.execute(sql, (item.id, item.title, item.order))
30.
31.
# Write the new info to db
32.
self
.connection.commit()
[ Source ]