summaryrefslogtreecommitdiff
path: root/python/skytools/psycopgwrapper.py
diff options
context:
space:
mode:
authorMarko Kreen2009-02-13 10:03:53 +0000
committerMarko Kreen2009-02-13 12:21:01 +0000
commit5521e5fc2f399a923fa7fb313bbe797cfa0d5baa (patch)
tree7df01ec195273b812bc9b64953a71ad1155d9438 /python/skytools/psycopgwrapper.py
parent012aee6a0369d8a4b2617046a27659c02b0bb478 (diff)
python/skytools update
- docstrings - some preliminary python 3.0 compat (var names, print()) - sync with 2.1-stable adminscript: - move exec_cmd function to dbscript dbstruct: - support sequnces. SERIAL columns are not automatically created, but the link beteween column and sequence is. psycopgwrapper: - drop support for psycopg1 - beginnings of quick DB-API / DictRow description. quoting: - new unquote_fqident() function, reverse of quote_fqident() - quote_statement() accepts both row and dict dbscript: - catch startup errors - use log.exception for exceptions, will result in nicer logs sqltools: - exists_sequence() _pyquoting: - fix typo in variable name
Diffstat (limited to 'python/skytools/psycopgwrapper.py')
-rw-r--r--python/skytools/psycopgwrapper.py59
1 files changed, 52 insertions, 7 deletions
diff --git a/python/skytools/psycopgwrapper.py b/python/skytools/psycopgwrapper.py
index 9d23e506..7bce0c33 100644
--- a/python/skytools/psycopgwrapper.py
+++ b/python/skytools/psycopgwrapper.py
@@ -1,16 +1,60 @@
-"""Wrapper around psycopg1/2.
+"""Wrapper around psycopg2.
-Preferred is psycopg2, fallback to psycopg1.
+Database connection provides regular DB-API 2.0 interface.
-Interface provided is psycopg1:
- - dict* methods.
- - new columns can be assigned to row.
+Connection object methods::
-"""
+ .cursor()
+
+ .commit()
+
+ .rollback()
+
+ .close()
+
+Cursor methods::
+
+ .execute(query[, args])
+
+ .fetchone()
+
+ .fetchall()
+
+
+Sample usage::
-import sys
+ db = self.get_database('somedb')
+ curs = db.cursor()
+
+ # query arguments as array
+ q = "select * from table where id = %s and name = %s"
+ curs.execute(q, [1, 'somename'])
+
+ # query arguments as dict
+ q = "select id, name from table where id = %(id)s and name = %(name)s"
+ curs.execute(q, {'id': 1, 'name': 'somename'})
+
+ # loop over resultset
+ for row in curs.fetchall():
+
+ # columns can be asked by index:
+ id = row[0]
+ name = row[1]
+
+ # and by name:
+ id = row['id']
+ name = row['name']
+
+ # now commit the transaction
+ db.commit()
+
+Deprecated interface: .dictfetchall/.dictfetchone functions on cursor.
+Plain .fetchall() / .fetchone() give exact same result.
+
+"""
+# no exports
__all__ = []
##from psycopg2.psycopg1 import connect as _pgconnect
@@ -54,6 +98,7 @@ class _CompatCursor(psycopg2.extras.DictCursor):
class _CompatConnection(psycopg2.extensions.connection):
"""Connection object that uses _CompatCursor."""
+ my_name = '?'
def cursor(self):
return psycopg2.extensions.connection.cursor(self, cursor_factory = _CompatCursor)