I. Installation of relevant packages

npm install access-db


npm install dotenv

Then create a new.env file at the beginning of the project entry file (such as app.js) with require(‘dotenv’).config() and add the MySQL configuration.

MYSQL_HOST=localhost // mandatory MYSQL_USER=root MYSQL_PASSWORD=123456 MYSQL_PORT=3306 MYSQL_DATABASE= // mandatory

Transaction (); Transaction ();

Asynchronous function for transaction processing

let { run, begin, rollback, commit, locks } = await mysql.transaction()

parameter type mandatory instructions
begin Function is Transaction start function
commit Function is Transaction commit function
rollback Function no Rolls back the transaction function
run Function is Execute SQL statement functions
locks Object no Locking type

Details of the locks

field value instructions
shared_locks ‘ lock in share mode’ Shared Locks are common Locks that lock rows.
exclusive_locks ‘ for update’ This lock Locks Exclusive Locks on rows. This lock Locks Exclusive Locks on rows.

Begin () starts the transaction function, performs the database operation in the begin() function, executes the individual SQL statements through run(), and returns the results. The rollback() function can be used to perform rollback operations when an error is reported, or when the SQL result executed does not meet the criteria. When execution is fine, remember to commit the transaction, which is to execute the commit() function.

If you need something like a seckill business. Then you also need to lock the data by adding the type of locks immediately after the return SQL statement.

Sample code:

Import {mysql} from 'access-db' /** mysql */ let {run, begin, rollback, commit, Lock} = await mysql.transaction() await begin(async () => {try{// When a lock is required, add the lock to the end of the SQL statement. Let sql1 = (await mysql.get('user', 10, 'sentence')) + locks.exclusive_locks let sql2 = await mysql.update('user', 10, {money: ['incr', -3]}, 'sentence') let sql3 = await mysql.update('user', 12, {money: ['incr', 3]}, 'sentence') let res1 = await run(sql1) if(res1.data.money < 3){return await rollback() // rollback transaction} await run(SQL2 Run (SQL3) await commit() // commit transaction}catch(err){await rollback() // throw new Error(err)})