Sadly, when you prepare an insert statement with a particular set of fields using placeholders, the "default" value for a given field in the mysql table definition will never be applied, ever -- even when the associated variable is undef.
To handle that in a way that does not require database details to be embedded in your perl script, you have to use a flexible method of preparing the statement, so that you can leave out fields when their associated values are empty:
(that assumes use of RaiseError => 1 in the DBI->connect call to handle error checking).sub add_foo { my @expected_fields = qw/bar blah/; my ( @insert_flds, @insert_vals ); for my $f ( @expected_fields ) { my $v = shift; next unless ( defined( $v ) and length( $v )); push @insert_flds, $f; push @insert_vals, $v; } my $sth = $dbh->prepare_cached( 'insert into foo (' . join( ',', @insert_flds ) . ') values (' . join( ',', ('?') x @insert_flds ) . ')' ); $sth->execute( @insert_vals ); return $dbh->last_insert_id( undef, undef, 'foo_id' )); }
In reply to Re: Using MySQL table's default values upon insert
by graff
in thread Using MySQL table's default values upon insert
by Zettai
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |