in reply to Re: SQL: Update column(s) value with extra WHERE
in thread SQL: Update column(s) value with extra WHERE
(1) Prepare once, use many times. This statement, my $sth_upd = $dbh->prepare($stmt); should be outside the loop. In general, preparing is an "expensive" operation. The DB can wind up doing quite a bit of work while making its execution plan. Typically you want to put prepare statements outside of the loop. Prepare once before the loop and then use it many times within the loop. Of course, I presume that the automatic SQL statement generator gizmo does a fair amount of futzing around. Those statements should also go above the loop.
(2) Transactions are expensive. By default, each update is a separate transaction. You want to leave autocommit enabled and use $dbh->begin_work and $dbh->commit to bracket a loop with many updates. In rough numbers, say you can do 10 transactions per second. An update with 100 rows would take 10 seconds. However, if you put all 100 updates into one transaction, you could get the job done in 1 second. This order of magnitude, 10:1 performance increase is typical and will matter in a DB of any significant size.
(3) This isn't a performance issue, but this error handling is not the best way.
Using the RaiseError attribute when opening the DB connection will get automatic error checking/die for you. So you would just need $sth_upd->execute(@bind); Furthermore if this update is being run as one of many updates comprising a single transaction, the transaction will either 100% succeed or totally fail.if( ! $sth_upd->execute(@bind) ){ $dbh->rollback(); die "update (and rolling back): ".$dbh->errstr; }
When the transaction starts, SQLite will create one or more files for journaling. When the transaction is committed, the DB is actually updated and these files are removed. If the program dies during the transaction, the DB is not actually updated at all and these journal files remain. The next time you connect to the SQLite DB, the driver will see this uncompleted transaction in process and will "cancel it out" and remove the journal files. You should then just correct whatever the problem was and run all of the updates again. There is no need in this case for a "rollback". The updates in the failed transaction are "like it never even happened".
These concepts are demo'ed my code further down in the thread.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: SQL: Update column(s) value with extra WHERE
by bliako (Abbot) on Jul 17, 2023 at 22:00 UTC | |
by Marshall (Canon) on Jul 18, 2023 at 06:32 UTC | |
by NERDVANA (Priest) on Jul 19, 2023 at 02:32 UTC | |
by eyepopslikeamosquito (Archbishop) on Jul 19, 2023 at 09:12 UTC | |
by bliako (Abbot) on Jul 19, 2023 at 07:26 UTC | |
Re^3: SQL: Update column(s) value with extra WHERE
by Anonymous Monk on Jul 16, 2023 at 19:45 UTC | |
by Marshall (Canon) on Jul 17, 2023 at 09:11 UTC |