Hi all,

I am curious to know if there is a "cleaner" way to check for and handle NULL values, when processing the result set of an SQL query.
Please consider the following code (assume -w and use strict):
178 # Build the first half of the INSERT 179 # using the field list we got from the earlier DESCRIBE 180 # Of course we only do this if we have any rows to inser +t 181 if ($affected_rows) { 182 my $base_insert = "INSERT IGNORE INTO $thisTable (host +name, host_id, " 183 . join("," , @fields) 184 . ") VALUES (\"$site_hostname\", \"$site_id\", "; 185 186 # Now we iterate through the result set from the pre +vious query 187 # completing each INSERT as we go, and dumping them +all into a big list 188 while (my @row = $dbq->fetchrow_array) { 189 # Need to check for NULL's 190 for(@row) { $_ = "NULL" if !defined $_; } 191 my $this_insert = $base_insert 192 . join("," , map {qq("$_")} @row) 193 . ");"; 194 push @central_inserts, $this_insert; 195 } 196 }
The above code is part of a script that is used to backup tables from several remote hosts to a central database. It works "okay", but after running it a few times I discovered that it wasn't correctly handling NULL's.
So I inserted:
for(@row) { $_ = "NULL" if !defined $_; }
at line 190.

Is that a reasonable approach?
Is there a better (cleaner) way?

Thanks,
--Darren

In reply to DBI - Handling NULL values by McDarren

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.