[Zope-Perl] dbi

Gisle Aas gisle@ActiveState.com
23 May 2000 23:14:51 +0200


I now have a working DBI module for python.  The following test
program access a local Mysql database on my home Linux box.

-------------------------------------------------------------------
#!/usr/bin/env python

import dbi

dbh = dbi.connect("DBI:mysql:database=fotodb", "gisle",
                  RaiseError = 1,
                  PrintError = 0,
                  AutoCommit = 1,
                 );

sth = dbh.prepare("select * from img limit 5")
rows = sth.execute()
print rows

while 1:
        row = sth.fetchrow_tuple()
        if not row: break
        print row

dbh.disconnect()

---------------------------------------------------------------------


$ python dbi-test.py 
5
('1', 'jpg', '1967-10-08', '4 generasjoner Usterud-Hanssen', '1762', '1154', None, None, 'n', '197910', 'f9595f651a4344ba384c5e2d2c888ecb', '1999-10-08 21:37:52')
('2', 'jpg', '1967', None, '1396', '1991', None, None, 'n', '243423', 'e98c5b8a1452627b1d6edb732143be74', '1999-10-08 21:37:53')
('3', 'jpg', '1976', None, '386', '533', None, None, 'n', '15995', '4e24b4f6e73ac03af516e73fcd4e7beb', '1999-10-08 21:37:53')
('4', 'jpg', '1986', None, '454', '531', None, None, 'n', '17232', 'cce10dfbb4c6854eb3a6e11341bc997f', '1999-10-08 21:37:53')
('5', 'jpg', '1995', None, '1122', '1592', None, None, 'n', '188945', '40f24ccfc89bad8ca27b5a5b8d515bef', '1999-10-08 21:37:53')


The dbi.py file looks like this:
-------------------------------------------------------------------

# Perl DBI adaption for python

import perl

perl.eval("""

use strict;
require DBI;

package Python::Util;

# define some helper functions for dict2hash()

sub make_hash {
        {}
}

sub hash_elem {
        my $hash = shift;
        my $key  = shift;
        my $old = $hash->{$key};
        $hash->{$key} = shift if @_;
        $old;
}

""")

def connect(data_source, username, password="", **attr):
        dbh = perl.callm("connect", "DBI", data_source, username, password,
                                    dict2hash(attr))
        return dbh

def available_drivers():
        # XXX need a way to call static methods in array context
        return perl.callm("available_drivers", "DBI")

def dict2hash(dict):
        hash = perl.call("Python::Util::make_hash")
        for k in dict.keys():
                perl.call("Python::Util::hash_elem", hash, str(k), dict[k])
        return hash

----------------------------------------------------------------

Regards,
Gisle