Node.js Connection Pools, Parameterized Queries, and Transactions

Read and write MySQL safely in Node.js and run transactions on a single connection

🎯 Introduction

By the end of this article, you will be able to read and write MySQL safely in Node.js and run transactions on a single connection.

This article queries and updates Xiao Ming in blog_demo.user. The record is shown below, with other columns omitted:

idusername
1Xiao Ming

Initialize the user table as described in Databases and CRUD. The transaction below also appends records to user_change from the transactions article, where user_id stores the user ID and new_city stores the new city.


🔐 Create an account for Node.js database connections

Node.js also needs a username and password to connect to MySQL. The course_app account created here is a MySQL account specifically for the backend. Add it to the connection configuration later so the program can query and update data.

It differs from Xiao Ming in the user table: course_app logs in to the database; Xiao Ming is an application data record stored in it. Creating course_app does not insert a record into user.

Why not keep using root?

root administers MySQL, including creating accounts and granting privileges. The backend usually only needs to read and write application tables, so give it a separate account with those privileges. A statement attempting to delete the database will then be rejected for insufficient privileges.

Log in as root, then create the account

Using the Docker container from the getting-started article, run this in your terminal:

docker exec -it mysql-course mysql -uroot -p

This opens the container's MySQL command line as root; -p prompts for the root password. Enter the password set when creating the container. At mysql>, execute:

CREATE USER 'course_app'@'%' IDENTIFIED BY 'LocalApp_84_only';

This creates a MySQL account. Its components mean:

SyntaxMeaning
CREATE USERCreate a database login account
'course_app'Account name, later used as DB_USER
@'%'Allow connections from any source host, still requiring password authentication
IDENTIFIED BY 'LocalApp_84_only'Set the password, later used as DB_PASSWORD

A successful execution displays Query OK. The account now exists but cannot yet read or modify blog_demo. Create it once, rather than each time Node.js starts.

The local example uses % to allow connections through Docker networking. It describes permitted client origins, not the database address. This course binds the container port only to local 127.0.0.1. For deployment, restrict source hosts and network access and replace the practice password.

Allow the account to read and write blog_demo tables

Continue in the current root mysql> session:

GRANT SELECT, INSERT, UPDATE, DELETE ON blog_demo.* TO 'course_app'@'%';

This grants course_app permission to select, insert, update, and delete records in every table in blog_demo.

SyntaxScope of permitted operations
SELECT, INSERT, UPDATE, DELETERead, insert, update, and delete table records
ON blog_demo.*Only tables in blog_demo; the asterisk means all tables
TO 'course_app'@'%'Grant these privileges to the account just created

Success again displays Query OK. The account can delete user records, but it cannot drop tables, drop databases, or change table structures. An administrative account still performs those operations.

Verify the privileges before using the account in Node.js

Still as root, inspect the grants:

SHOW GRANTS FOR 'course_app'@'%';

After creating the account and granting the privileges above, the main output is:

Grants for course_app@%
GRANT USAGE ON . TO course_app@%
GRANT SELECT, INSERT, UPDATE, DELETE ON blog_demo.* TO course_app@%

USAGE alone grants no data access. The four privileges on blog_demo in the second row confirm that the account can read and write the practice database.

Enter exit to return to the terminal. Next, install the driver and configure Node.js using course_app and the LocalApp_84_only password you set, rather than root credentials.


📦 Install the driver and configure the connection

This article uses Node.js 24.19.0 and mysql2 3.11.5, with ESM examples in .mjs files. mysql2 is the driver connecting Node.js to MySQL:

npm install mysql2@3.11.5

Create .env in your practice directory with the new database account. DB_HOST and DB_PORT identify the MySQL server, DB_USER and DB_PASSWORD authenticate the connection, and DB_NAME selects the database:

DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=course_app
DB_PASSWORD=LocalApp_84_only
DB_NAME=blog_demo

Add .env to .gitignore. If you changed the local port to 3307, update it here too. For remote databases, enable TLS transport encryption according to the provider's instructions rather than disabling certificate verification.


🔌 Create a reusable connection pool

Create db.mjs:

db.mjs
import mysql from 'mysql2/promise';

export const pool = mysql.createPool({
    host: process.env.DB_HOST,
    port: Number(process.env.DB_PORT || 3306),
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    connectionLimit: 5
});

A connection pool keeps reusable database connections so each user query does not require reconnecting. connectionLimit caps the connections this pool can use simultaneously. Five is a local practice setting, not a universal recommendation. Each service process has its own pool, so account for the combined connection count.


🔎 Read users with parameterized queries

Create query-user.mjs:

query-user.mjs
import { pool } from './db.mjs';

try {
    const [rows] = await pool.execute(
        'SELECT id, username FROM user WHERE id = ?', [1]
    );
    console.log(rows);
} finally {
    await pool.end();
}

Run:

node --env-file=.env query-user.mjs

With the earlier data intact, the script prints an array of objects. Displaying its rows as a table gives:

idusername
1Xiao Ming

No match produces an empty array with no data rows. mysql2 returns rows as the first item and field metadata as the second; this example uses only the rows.

execute uses prepared statements, handling SQL structure separately from parameter values. The question mark represents one data value, supplied by 1 in the second argument. Even input containing SQL text is treated only as a value.

Question marks cannot replace table names, column names, or sort directions. Select dynamic sort columns from a fixed backend allowlist. Do not concatenate user input into SQL before passing it to execute.


✏️ Write results are not data rows

In a separate script, check whether an update matched its target like this:

update-user.mjs
import { pool } from './db.mjs';

try {
    const [result] = await pool.execute(
        'UPDATE user SET city = ? WHERE id = ?', ['Suzhou', 1]
    );
    console.log(result.affectedRows);
} finally {
    await pool.end();
}

Run it the same way as the query script, replacing the filename. With mysql2's defaults, UPDATE affectedRows reports matched rows, not necessarily changed values. Interpret it according to any additional conditions, such as requiring the old and new values to differ. For INSERT, insertId provides the generated auto-increment ID.


Create change-city.mjs with the application operation first. The caller supplies connection, ensuring both SQL statements use the same connection:

change-city.mjs
export async function changeCity(connection, id, city) {
    const [result] = await connection.execute(
        'UPDATE user SET city = ? WHERE id = ?', [city, id]
    );
    if (result.affectedRows !== 1) throw new Error('User not found');
    await connection.execute(
        'INSERT INTO user_change (user_id, new_city) VALUES (?, ?)', [id, city]
    );
}

If the update matches no user, throw an error instead of saving a change record for a nonexistent user. This is an application rule, not an error the database automatically raises.


✅ Borrow a connection before starting the transaction

Create transaction-demo.mjs and first import and borrow a connection:

transaction-demo.mjs
import { pool } from './db.mjs';
import { changeCity } from './change-city.mjs';

const connection = await pool.getConnection();

Continue in the same file with the complete transaction flow:

transaction-demo.mjs
try {
    await connection.beginTransaction();
    await changeCity(connection, 1, 'Chengdu');
    await connection.commit();
    console.log('City and change record saved');
} catch (error) {
    await connection.rollback();
    throw error;
} finally {
    connection.release();
    await pool.end();
}

beginTransaction starts the transaction, changeCity performs both writes, and commit commits them together. On failure, catch calls rollback to undo uncommitted changes and rethrows the error to the caller. finally runs on either outcome, and release returns the connection to the pool.

Run node --env-file=.env transaction-demo.mjs. Success prints “City and change record saved”. Change the user ID to a nonexistent one and run again: expect “User not found” and no new change record.

pool.end lets this one-off practice script finish. An HTTP service should reuse its pool and close it only when the service shuts down, rather than after every request.


❓ Questions and Answers

Q1: Do I need release after pool.execute?

No. It borrows and returns a connection automatically. Explicit release is needed only for connections you borrow with getConnection.

Q2: Can I start a transaction with pool.query and then update with pool.execute?

Those calls are not guaranteed to use the same connection. Perform every transaction operation through the borrowed connection.

Q3: Can both query and execute use question marks?

Yes, but their mechanisms differ. query generally formats parameters in the driver; execute uses server-side prepared statements. This course uses execute consistently for parameterized reads and writes.


🧪 Exercise

Change the transaction's user ID to 999 and confirm that failure adds no user_change record. Restore ID 1 and verify success.

// Write your code or record your verification results here