Updating Data
Class
RWDBUpdater is used to update database tables. An updater is obtained by requesting one from a database table, and it may be supplied with an
RWDBCriterion to express a restriction on the rows to be updated. You express a restriction by using a
where() method, just as with
RWDBSelector.
An updater must be told which columns to update, and which new values to use. You do this by supplying the updater with one or more
RWDBAssignment instances. These
RWDBAssignment instances are created anonymously when you call the
assign() method of
RWDBColumn. The insertion operator
<< is used to add the assignments to an updater:
int videoID = 1234;
int supplierID = 11;
int quantity = 12;
RWDBTable purchases = myDbase.table("purchase");
RWDBUpdater update = purchases.updater(); //1
update << purchases["supplierID"].assign(supplierID) //2
<< purchases["quantity"].assign(quantity); //3
update.where(purchases["videoID"] == videoID); //4
update.execute(myConnection); //5
On
//1, an
RWDBUpdater is obtained for the
purchase table. Lines
//2 and
//3 add two
RWDBAssignment instances and two
RWDBColumn instances to the updater anonymously, and
//4 sets the
WHERE clause.
The result is equivalent to an SQL statement like:
UPDATE purchases
SET supplierID = 11, quantity = 12
WHERE videoID = 1234
When the
execute() method is invoked on
//5, the
purchase table in the database is updated. As discussed with regard to
RWDBInserter, the
execute() method returns an
RWDBResult, which may be ignored.
Note the importance of the where() call on //4. If this were omitted, no restriction would be placed on the update, resulting in an update of all rows within the purchase table.
NOTE: Executing an updater without first assigning a criterion causes all rows in the table to be updated.
Once a criterion has been assigned to an updater using the where() method, that criterion is retained. The where() method can be called at any time to set a new criterion, or it can be called with an empty criterion to clear the criterion.
As with
RWDBInserter, we recommend using an explicit connection when executing an update.