hubert's home

a bunch of things unix, java, programming, pc gaming, poker, and personal randomness

Thursday, March 24, 2005

Class::DBI

I've never looked at this package before, but Class::DBI looks like a great perl package for database abstraction. If you have a mysql database named 'emaildb' with a list of table named 'emailtable' and 1 column of emails named 'email', this code is all you need to do print out that list. No SQL required.

#!/usr/bin/perl
package email;
use base 'Class::DBI';

email->connection('dbi:mysql:emaildb','user','password');
email->table('emailtable');
email->columns(All => 'email');

package main;
@emails = email->retrieve_all();
print "All emails: @emails\n";

# or you can search for entries with
@search = email->search(email=>'random@nowhere.com');
print "Random emails: @search\n";



There's also iterators to iterate through results and a where clause builder so you can create more complex queries. Of course it can do much more complex things if you need to build your own SQL statements(which most non-trivial applications will need to do at some point). I just glanced quickly at the docs, but I'm sure there's more to it(and some caveats no doubt), but I am a fan of dynamic programming languages like perl that allow you to build data types at run time like this. I'm going to be sure to use this more in the future.

1 Comments: Post a Comment

Anonymous Will said:

Class::DBI is awesome! I just barely started reading up on it. It will make my database programming life much easier.

This article on it gave me goose bumps.

5:39 AM  

<< Home