Perl Monks,

I have a routine to update a number of rows for one column in a database table. I want to speed this up though because at the moment it runs an SQL update for each row. For approx 10000 it takes 2 secs.

sub process_urlhits_update{ my $sql1 = qq {UPDATE url_table SET hits}; my $sql2 = qq {WHERE url}; my $sql; foreach my $url ( keys %urlhits_update ){ $sql= qq { $sql1=$urlhits_update{$url} $sql2="$url" }; my $sth = $dbh->prepare( $sql ); $sth->execute(); $urlid_hash{$url}=get_urlid($url) if ! defined $urlid_hash{$ur +l}; delete $urlhits_update{$url}; } }

I tried changing the code to write to a file and then run one SQL command to LOAD FILE. This runs quicker at about 1.3 secs for 10000 rows:

sub process_urlhits_update{ my $sql1 = qq {\nUPDATE url_table SET hits}; my $sql2 = qq {WHERE url}; my $sql; open(FH,">/tmp/updates.txt")||die("could not open updates file"); foreach my $url ( keys %urlhits_update ){ $sql .= qq { $sql1=$urlhits_update{$url} $sql2="$url" }; $urlid_hash{$url}=get_urlid($url) if ! defined $urlid_hash{$ur +l}; delete $urlhits_update{$url}; } print FH $sql; $sql="LOAD DATA LOCAL INFILE '/tmp/updates.txt' INTO TABLE url_tab +le"; my $sth = $dbh->prepare( $sql ); $sth->execute(); }

However, my 2 routines which do bulk SQL inserts only take 0.26 secs.

Is there anything I can do to improve my code above? For example, can I run LOAD FILE without actually writing to disk ? or can you do bulk updates?

Thanks as always for your wisdom.

js.


In reply to speedy update routine by js1

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.