tags:

views:

310

answers:

1

Seems that it may not be possible, but hey I might as well ask, I could be wrong. Was wondering if there's anyway for perl to update multiple rows using one MySQL call, I'm using DBI.

Any help or feedback would be greatly appreciated, this is possible in MSSQL through ASP and ASP.net so was wondering if also possible through perl on MySQL.

Thank you for your feedback!

+12  A: 

First and most important, you absolutely should not interpolate variables directly into your SQL strings. That leaves open the possibility of SQL injection attacks. Even if those variables don't come from user input, it leaves open the possibility of dangerous bugs that can screw up your data.

The MySQL DBD driver does support multiple statements, though it's turned off by default as a safety feature. See mysql_multi_statements under the Class Methods section in the DBD::mysql documentation.

But a much better solution, which solves both problems at once and is more portable, is to use prepared statements and placeholder values.

my $sth = $dbh->prepare("UPDATE LOW_PRIORITY TableName SET E1=?,F1=? WHERE X=?");

Then, get your data in a loop of some sort:

while( $whatever) { 
    my ( $EC, $MR, $EM ) = get_the_data();
    $sth->execute( $EC, $MR, $EM );
}

You only need to prepare the statement once, and the placeholder values are replaced (and guaranteed to be properly quoted) by the DBD driver.

Read more about placeholders in the DBI docs.

friedo
The "DBD driver" is just the backend-specific driver used by DBI, such as DBD::mysql. You don't need to be concerned about the connections, though, in any case - so long as you keep reusing the same `$dbh` to run the statements, you'll be using the same database connection and the 'prepare once, execute many' model demonstrated by friedo will be more efficient than passing many queries in a single string, as it avoids the overhead of having to parse (prepare) each query individually.
Dave Sherohman
@mastermind: interpolation is always bad, no matter what the application; many vulnerabilities arise from programmer error rather than user mischief.
Ether