Are you looking for performance benefits from using prepare and binding parameters, or security benefits, or code-cleanliness benefits, or?...

To get the security benefits, I'll often maintain two parallel structures: one with the query with parameters replaced by ?, and another with all of the parameters that should be used in execute. For example:

$query .= ' where upper(env)=upper(?)'; push(@sql_params,$query(env}); ... my $sth = $dbh->prepare($query) or die; $sth->execute(@sql_params);

Getting the performance benefits isn't as easy, but there aren't performance benefits unless you're in a long-running environment (like mod_perl) and frequently repeat the same query. If that's the case, if you can come up with a few parameterized queries, you can prepare all of them, then just pick the right one. For example, it looks like there are only 8 possibilities in your sample code, so you could store these 8 queries in an array, then pick the right one and send it the right parameters.

Also, you can simplify the way you append to the query by using an array and join (untested, but you get the idea):

if (defined($query{component})) push(@querypart, 'where upper(component) = upper(?)'; push(@sql_params,$query{component}); } if (defined($query{env})) { push(@querypart, 'where upper(env) = upper(?)'; push(@sql_params,$query{env}); } $query = 'SELECT * FROM or_mod ' . join(' AND ',@queryparts) . ' order by env, application, component, mod_date, desc'; print $query; my $sth = $dbh->prepare($query); $sth->execute(@sql_params);

In reply to Re: Looking for neater solution with dynamic query by sgifford
in thread Looking for neater solution with dynamic query by pg

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.