简体   繁体   中英

MySQL database query and update

I was wondering if somebody knew a better way to do the following:

I need to query a database and return a value (in this case an int), then using this value, calculate the new value and update the database with this new value.

My current approach is using a method to get the current int value from the database, passing this value to another method to perform the calculations and then passing the new value to a third method to update the database.

So, the problem(?) with this is that it opens a new connection from the pool when getting the initial value from the db and then when updating it. Obviously it closes the connection at the end of the method but is there some easier / better way of doing this ? It seems a bit messy.

You don't have to open a new connection for each query. Just open a connection at the start of your request, save its reference to a global variable that you can use in all your methods, and close it at the end of your request.

Try this:

 SELECT fieldValue FROM table_name FOR UPDATE;
 UPDATE table_name SET fieldToUpdate = fieldValue + 1;

See the UPDATE Syntax

If you can do the calculations in SQL:

UPDATE TableToUpdate
SET ColumnB = 
    Calculations( ( SELECT ColumnA
                    FROM TableToSelect
                    WHERE (conditions for selecting)
                  )
                )
WHERE (conditions for updating)

Depending on your requirements you could exploit multiple-table UPDATE:

UPDATE TableToUpdate U JOIN TableToSelect S ON ( -- join condition for selection value to process )
SET U.ColumnB = Calculations( S.ColumnC )
WHERE U.ColumnC = -- whatever selection condition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM