Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

named placeholders in DBI

by risacher (Beadle)
on Sep 22, 2003 at 16:07 UTC ( [id://293171]=perlmeditation: print w/replies, xml ) Need Help??

How many times have you written code that looks like this:
$dbh->do(qq{INSERT INTO files (file, dev, ino, mode, nlink, uid, gid, rdev, size, atime, mtime, ctime, md5sum, bz2size, disc, newfile) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )}, undef, $filename, $dev, $ino, (sprintf "%lo", $mode), $nlink, $ui +d, $gid, $rdev, $size, $atime, $mtime, $ctime, $digest, undef, undef, undef);
?

I discovered recently that most DBD's allow you to use named placeholders if you use the bind_param function. Even if it's less concise, I think this is a good idea for readability and maintainability.

So instead of doing this:

$sth = $dbh->prepare('SELECT * FROM modules WHERE module LIKE ? AN +D code LIKE ?'); $rv = $sth->execute('%v%', '%x%');
You can do this:
$sth = $dbh->prepare('SELECT * FROM modules WHERE module LIKE :m A +ND code LIKE :c'); $sth->bind_param(':m', "%v%"); $sth->bind_param(':c', "%x%"); $rv = $sth->execute;
Sure, it's wordier, but you'll never count question-marks again! Plus, you can edit your SQL later; moving the placeholders won't matter.

Caveat... DBD:Pg seems to only allow one-character placeholders. I don't know why.

Replies are listed 'Best First'.
Re: named placeholders in DBI
by vladb (Vicar) on Sep 22, 2003 at 16:39 UTC
    This is of course true unless you are dealing with an automated process of building your queries from predefined perl structures. This would especially apply to building insert queries where data to be inserted is stored in a convenient perl hash (with keys being the fields and values being the corresponding field values :).

    For example,
    # a new record to be inserted my %user_rec = ( first_name => 'Foo', last_name => 'Bar', phone => '12345678', address => '123 Foo St', ); ## ## . . . some code here . . . ## # possibly somewhere in an add_db_user() sub # ... my @fields = keys %user_rec; my @values = @user_rec{@fields}; my $placeholders = join(",", ("?") x scalar @fields); my $sql = sprintf(qq~ INSERT INTO user(%s) VALUES(%s) ~, join(",", @fields), $placeholders); my $sth = $dbh->prepare($sql); $sth->execute(@values);
    In this specific example the query would be:
    INSERT INTO user(first_name,address,last_name,phone) VALUES(?,?,?,?)
    Introducing placeholders here may not be as useful or productive as say in a case where you build your SQL query 'manually'. ;)

    _____________________
    "We've all heard that a million monkeys banging on a million typewriters will eventually reproduce
    the entire works of Shakespeare. Now, thanks to the Internet, we know this is not true."

    Robert Wilensky, University of California

      This functionality is also available pre-rolled in DBIx::SQLEngine:
      my ($sql, @params) = DBIx::SQLEngine->sql_insert( table => 'users', values => \%user_rec );

      There's also a dbh wrapper method that allows you to prepare and execute the query in one go:

      my $sqldbh = DBIx::SQLEngine->new( ... ); # same args as DBI->connect ... $sqldbh->do_insert( table => 'users', values => \%user_rec );
Re: named placeholders in DBI
by tantarbobus (Hermit) on Sep 22, 2003 at 22:21 UTC

    1. DBD::mysql does not support named placeholders. 2. The current version of DBD::Pg does not support named placeholders even thought they might work. What you are seeing is some legacy code from DBD::Oracle that was left in the driver code, but it does not work as it should, and is not well tested. The next version of DBD::Pg will have full support named placeholders, however.

    You can get the latest beta here: http://search.cpan.org/CPAN/authors/id/R/RU/RUDY/DBD-Pg-1.31_5.tar.gz

Re: named placeholders in DBI
by mpeppler (Vicar) on Sep 22, 2003 at 17:40 UTC
    Note that DBD::Sybase does NOT support this syntax (or at least not yet).

    Michael

Re: named placeholders in DBI
by simonm (Vicar) on Sep 22, 2003 at 21:28 UTC
    That syntax is nice and clear, but the reduced portability makes me cautious...
Re: named placeholders in DBI
by Juerd (Abbot) on Sep 24, 2003 at 14:03 UTC

    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ... you'll never count question-marks again!

    Having a greedy everything-slurping placeholder helps too. Imagine you could use "(??)" to mean "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )". Wouldn't that be great? See DBIx::Simple.

    Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

      Most of the time I use this:

      $db->prepare('EXEC ImportLocale '. join(', ',('?') x 6));

      Jenda
      Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
         -- Rick Osborne

      Edit by castaway: Closed small tag in signature

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://293171]
Approved by jeffa
Front-paged by grinder
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (1)
As of 2024-04-25 07:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found