in reply to Looking for a simpler DBI solution.

I think you'll find that, when working with complicated databases, you'll often wind up with large statements like that. One (bad) way to simplify:

sub add_customer{ my $sth = $dbh->prepare('INSERT INTO customers VALUES (?,?,?,?,?,? +,?,?,?,?,?,?)'); die "Couldn't add customer" unless defined $sth; $sth->execute( @_ ); }

One thing you could do to simplify your code is to pass all fields as hashrefs with keys being the field names and values being data. Then you could do this (untested):

sub add_customer { # $data_hash is a hashref representing the fields # in the customers table that will be filled. my ( $data_hash ) = @_; my ( $fields, $values, $place_holders ) = format_insert_data( $dat +a_hash ); my $sth = $dbh->prepare( "INSERT into customers ( $fields ) VALUES + ( $place_holders )" ); $sth->execute( @$values ); } sub format_insert_data { # Takes a hash ref with keys being field names and # values being the values to insert into the database and # returns a list of fields, values, and placeholders suitable for +an SQL INSERT statement: # INSERT into table ( $fields ) VALUES ( $place_holders ) my ( $hash_ref ) = @_; if ( ref $hash_ref ne 'HASH' ) { croak "Argument to format_insert_data must be a hash reference +"; } my @fields = keys %$hash_ref; my $fields = join ',', @fields; my @values = @$hash_ref{ @fields }; my $place_holders = '?,' x scalar @fields; chop $place_holders; # remove trailing comma return ( $fields, \@values, $place_holders ); }

The problem with that, of course, is that it doesn't allow for data validation. However, the way to handle validation depends greatly upon your database. However, then all of your add_foo methods can be a wrapper around a generic add subroutine with the argument being the table and the data hash.


Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.