Generating dynamic SQL statements and need to plug in bind values? Maintain a single list of columns and let this function handle stringifications and preping your bind valuees array.
sub setup_bindings {
# Produces strings useful for generating dynamic
# SQL statements as well as an array of matching
# binding values (because you use bind values, right?)
#Args:
# $_[0]: Ref to hash of values, keyed by column
# $_[1]: Ref to array of columns used
#Usage:
# my ( $column_string, $bindings_string, $bound_values )
# = setup_bindings( \%value_for_column, \@columns );
# my $statement = " INSERT into YOUR_TABLE ( $column_string )
# VALUES ( $bindings_string )";
# $dbhandle->do( $statement, undef, @$bound_values ); #Or whatever
+use you have- this is `do` from the DBI
my $values = shift;
my @columns = @{ +shift };
my @set_columns = ();
my @set_bindings = ();
my @bound_values = ();
for my $col_2_bind ( @columns ) {
push @set_columns, $col_2_bind;
push @set_bindings, '?';
push @bound_values, $values->{$col_2_bind};
};
my $column_string = join ', ', @set_columns;
my $bindings_string = join ', ', @set_bindings;
return ($column_string, $bindings_string, \@bound_values);
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.