不可逆な毎日ブログ

2度と過ごすことのない毎日をつらつらと・・・

Python Database API

Python Database API Specification v2.0を調べてみた。

タプルで渡せば良いのか。
ということは、

>>> l = []
>>> l.append(1)
>>> l.append(2)
>>> l.append(3)
>>> l.append(4)
>>> l
[1, 2, 3, 4]
>>> t = tuple(l)
>>> t
(1, 2, 3, 4)

で、タプル化させれば良いのかな。
辞書は、キーのタプルになるのか。

>>> h = {}
>>> h["a"] = 1
>>> h["b"] = 2
>>> h
{'a': 1, 'b': 2}
>>> tuple(h)
('a', 'b')

やるなら、values()メソッドで値を取得後、タプル化みたい。

>>> h.values()
[1, 2]
>>> tuple(h.values())
(1, 2)

辞書を与えることもできるみたいだ。sample を見ていたらあった。
binary.py

data1 = {'id':1, 'name':'somehackers.jpg',
         'img':psycopg2.Binary(open('somehackers.jpg').read())}
data2 = {'id':2, 'name':'whereareyou.jpg',
         'img':buffer(open('whereareyou.jpg').read())}

curs.execute("""INSERT INTO test_binary
                  VALUES (%(id)s, %(name)s, %(img)s)""", data1)
curs.execute("""INSERT INTO test_binary
                  VALUES (%(id)s, %(name)s, %(img)s)""", data2)

これだな・・・。
PEP 249 -- Python Database API Specification v2.0

paramstyle

String constant stating the type of parameter marker
formatting expected by the interface. Possible values are
[2]:

'qmark' Question mark style,
e.g. '...WHERE name=?'
'numeric' Numeric, positional style,
e.g. '...WHERE name=:1'
'named' Named style,
e.g. '...WHERE name=:name'
'format' ANSI C printf format codes,
e.g. '...WHERE name=%s'
'pyformat' Python extended format codes,
e.g. '...WHERE name=%(name)s'

.execute(operation[,parameters])

Prepare and execute a database operation (query or
command). Parameters may be provided as sequence or
mapping and will be bound to variables in the operation.
Variables are specified in a database-specific notation
(see the module's paramstyle attribute for details). [5]

A reference to the operation will be retained by the
cursor. If the same operation object is passed in again,
then the cursor can optimize its behavior. This is most
effective for algorithms where the same operation is used,
but different parameters are bound to it (many times).

For maximum efficiency when reusing an operation, it is
best to use the .setinputsizes() method to specify the
parameter types and sizes ahead of time. It is legal for
a parameter to not match the predefined information; the
implementation should compensate, possibly with a loss of
efficiency.

The parameters may also be specified as list of tuples to
e.g. insert multiple rows in a single operation, but this
kind of usage is deprecated: .executemany() should be used
instead.

Return values are not defined.