Mysql
 sql >> Baza danych >  >> RDS >> Mysql

Transakcja mysql Node.js

Aktualizacja

Zobacz poniższą edycję składni async/await

Spędziłem trochę czasu na pisaniu uogólnionej wersji przykładu transakcji podanego przez node mysql, więc pomyślałem, że podzielę się nim tutaj. Używam Bluebird jako mojej biblioteki obietnic i użyłem jej do „obiecowania” obiektu połączenia, co znacznie uprościło logikę asynchroniczną.

const Promise = ('bluebird');
const mysql = ('mysql');

/**
 * Run multiple queries on the database using a transaction. A list of SQL queries
 * should be provided, along with a list of values to inject into the queries.
 * @param  {array} queries     An array of mysql queries. These can contain `?`s
 *                              which will be replaced with values in `queryValues`.
 * @param  {array} queryValues An array of arrays that is the same length as `queries`.
 *                              Each array in `queryValues` should contain values to
 *                              replace the `?`s in the corresponding query in `queries`.
 *                              If a query has no `?`s, an empty array should be provided.
 * @return {Promise}           A Promise that is fulfilled with an array of the
 *                              results of the passed in queries. The results in the
 *                              returned array are at respective positions to the
 *                              provided queries.
 */
function transaction(queries, queryValues) {
    if (queries.length !== queryValues.length) {
        return Promise.reject(
            'Number of provided queries did not match the number of provided query values arrays'
        )
    }

    const connection = mysql.createConnection(databaseConfigs);
    Promise.promisifyAll(connection);
    return connection.connectAsync()
    .then(connection.beginTransactionAsync())
    .then(() => {
        const queryPromises = [];

        queries.forEach((query, index) => {
            queryPromises.push(connection.queryAsync(query, queryValues[index]));
        });
        return Promise.all(queryPromises);
    })
    .then(results => {
        return connection.commitAsync()
        .then(connection.endAsync())
        .then(() => {
            return results;
        });
    })
    .catch(err => {
        return connection.rollbackAsync()
        .then(connection.endAsync())
        .then(() => {
            return Promise.reject(err);
        });
    });
}

Jeśli chcesz korzystać z puli zgodnie z sugestią w pytaniu, możesz łatwo zmienić createConnection wiersz z myPool.getConnection(...) i przełącz connection.end linie z connection.release() .

Edytuj

Zrobiłem kolejną iterację kodu za pomocą mysql2 biblioteka (to samo api co mysql ale z obsługą obietnicy) i nowymi operatorami asynchronicznymi/oczekiwania. Oto to

const mysql = require('mysql2/promise')

/** See documentation from original answer */
async function transaction(queries, queryValues) {
    if (queries.length !== queryValues.length) {
        return Promise.reject(
            'Number of provided queries did not match the number of provided query values arrays'
        )
    }
    const connection = await mysql.createConnection(databaseConfigs)
    try {
        await connection.beginTransaction()
        const queryPromises = []

        queries.forEach((query, index) => {
            queryPromises.push(connection.query(query, queryValues[index]))
        })
        const results = await Promise.all(queryPromises)
        await connection.commit()
        await connection.end()
        return results
    } catch (err) {
        await connection.rollback()
        await connection.end()
        return Promise.reject(err)
    }
}


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Odmowa dostępu dla użytkownika „root”@„localhost” podczas próby nadania uprawnień. Jak nadawać uprawnienia?

  2. PHPmailer - Wielokrotne wysyłanie e-maili

  3. java.sql.SQLException:Po zakończeniu wyniku ustawionego w mysql

  4. Host „xxx.xx.xxx.xxx” nie może połączyć się z tym serwerem MySQL

  5. Czy w MySQL można odzyskać więcej niż 1024 znaków z GROUP_CONCAT?