PerlClassDBI

ShscWiki :: LogIn :: PageIndex :: RecentChanges
Class::DBI is a very nice way to access a database in Perl.  With it you can do all of the normal DBI operations that you would expect with very little code.

Let's assume that you have a table called 'tickets' in a database called 'Tracker' that looks like this:

id int primary key auto_incriment name varchar(200) info varchar(200)


Now you want to be able to do normal operations on the data in the table quickly and easily right?  Here's how you do it:

You need to first create a class that you will use for a superclass everywhere else.  It has the login / password information as well as the database name.

Lets call this Auth.pm
package Auth; use base 'Class::DBI'; __PACKAGE__->set_main( 'Main', 'dbi:mysql:Tracker', 'LOGIN','PASSWORD' ); 1;


Next, for each table, create another class that uses the Auth class as a superclass.

package Tickets; use base 'Auth'; __PACKAGE__->set_db( 'Tickets' ); 1;


That's it for setting it up.  Now in your code you can do things like this:

use Tickets; my $cdbi = new Tickets; my $row = $cdbi->search_like( name => 'burt' ); print( "Error: 'burt' is not a valid name." ) unless $row; # Change his name to dave... # $row->name( 'dave' ); # Commit it to the database... # $row->save(); # Create a new record... # $row = $cdbi->create( name => 'durf', info => 'insert witty info here' ); # Delete the old one. # my $old_row = $cdbi->search_like( name => 'dave' ); $cdbi->delete( $old_row->id() ); # or... # $cdbi->delete( ($cdbi->search_like( name => 'dave' ))->id() );


This is just a quick taste of the things you can do with Class::DBI.  http://search.cpan.org/~tmtm/Class-DBI-0.96/lib/Class/DBI.pm has a list of all of the available commands.


This article is ©2008 by the respective authors. Reproduction is prohibited without express permission from all contributors.