in reply to Looking for neater solution with dynamic query
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);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Looking for neater solution with dynamic query
by eric256 (Parson) on Aug 24, 2005 at 22:27 UTC | |
by pg (Canon) on Aug 24, 2005 at 22:37 UTC |