Первое, что меня смутило при работе с БД в питоне — это невозможность вернуть результаты в виде хеша, только массив строк и столбцов. И это не поддерживается в DB API принципиально
Note that the reason for not extending the DB API specification
to also support dictionary return values for the .fetch*()
methods is that this approach has several drawbacks:
* Some databases don’t support case-sensitive column names or
auto-convert them to all lowercase or all uppercase
characters.
* Columns in the result set which are generated by the query
(e.g. using SQL functions) don’t map to table column names
and databases usually generate names for these columns in a
very database specific way.
As a result, accessing the columns through dictionary keys
varies between databases and makes writing portable code
impossible.
Но есть у курсора свойство .description которое можно использовать для получения массива столбцов и преобразование результатов в хеш.
-
def fetchdictall(cursor):
-
desc = cursor.description
-
dlen = len(desc)
-
ret = []
-
for item in cursor.fetchall():
-
onerow = {}
-
for field,i in zip(desc,range(dlen)):
-
onerow[field[0]] = item[i]
-
ret.append(onerow)
-
return ret
-
def executedict(cursor,*arg):
-
cursor.execute(*arg)
-
return fetchdictall(cursor)
Но у драйвера для постгриса есть уже встроено решение:
-
#!/usr/bin/python
-
import psycopg2,psycopg2.extras
-
dbc = psycopg2.connect("user=oduvan password='gr1v1ca5a' dbname=oduvan")
-
dbc.set_isolation_level(1)
-
cursor = dbc.cursor(cursor_factory=psycopg2.extras.DictCursor)
-
dbc.set_client_encoding('UNICODE')
-
cursor.execute('select * from "t1"')
-
ret = cursor.fetchall();
-
print ret[0]['name']
Статьи по теме:
http://www.devx.com/opensource/Article/29071/0/page/1
file:///usr/share/doc/python-psycopg2/doc/extensions.rst.gz
http://www.python.org/dev/peps/pep-0249/






У JQuery есть возможность парсить ХМЛ как текст, если передавать его как аргумент «волшебной функции»

Recent Comments