6

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!

1
  • in your example, there's no reason to not combine the two updates into one; can you give an example more like the updates you actually need to do? Commented Jan 3, 2010 at 16:17

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@mastermind: interpolation is always bad, no matter what the application; many vulnerabilities arise from programmer error rather than user mischief.
4

You don't need mysql_multi_statements, as friedo suggests.

You need turn off AutoCommit mode before you call the loop containing your UPDATE command:

**$dbh->{AutoCommit} = 0;**
while( $condition ) {
   my $myParam = something();
   ...
   $sth->execute( $myParam ); #your prepared UPDATE statement
   ...
}
**$dbh->commit();**

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.