Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MySQL Node.js Connection and Usage

MySQL Node.js Connection and Usage

MySQL is one of the most popular open-source relational databases, while Node.js is a JavaScript runtime environment based on the Chrome V8 engine. Combining the two can build powerful backend services.

Why choose MySQL + Node.js?

Install necessary dependencies

Before we begin, we need to install mysql2 package, which is a popular choice for connecting to MySQL in Node.js.



npm install mysql2

Why choose mysql2 instead of mysql?


Establish a database connection

Basic connection configuration

Example

const

mysql

=

require

(

'mysql2'

)

;

// Create a connection pool (recommended for production)

const

pool

=

mysql.

createPool

(

{

  host

:

'localhost'

,

   

// Database server address

  user

:

'root'

,

         

// Database username

  password

:

'password'

,

 

// Database password

  database

:

'test_db'

,

 

// Name of the database to connect to

  waitForConnections

:

true

,

  connectionLimit

:

10

,

 

// Maximum number of connections in the pool

  queueLimit

:

0

}

)

;

// Get a Promise-based connection

const

promisePool

=

pool.

promise

(

)

;

Connection pool vs single connection

Connection pool advantages:

When to use a single connection:


Perform basic CRUD operations

Query data (SELECT)

Example

async

function

getUsers

(

)

{

 

try

{

   

const

[

rows

,

fields

]

=

await promisePool.

query

(

'SELECT * FROM users'

)

;

    console.

log

(

rows

)

;

   

return

rows

;

 

}

catch

(

err

)

{

    console.

error

(

'Query error:'

,

err

)

;

   

throw

err

;

 

}

}

Insert data (INSERT)

Example

async

function

addUser

(

user

)

{

 

try

{

   

const

[

result

]

=

await promisePool.

query

(

     

'INSERT INTO users (name, email) VALUES (?, ?)'

,

     

[

user.

name

,

user.

email

]

   

)

;

    console.

log

(

'Insert ID:'

,

result.

insertId

)

;

   

return

result

;

 

}

catch

(

err

)

{

    console.

error

(

'Insert error:'

,

err

)

;

   

throw

err

;

 

}

}

Update data (UPDATE)

Example

async

function

updateUser

(

id

,

updates

)

{

 

try

{

   

const

[

result

]

=

await promisePool.

query

(

     

'UPDATE users SET name = ?, email = ? WHERE id = ?'

,

     

[

updates.

name

,

updates.

email

,

id

]

   

)

;

    console.

log

(

'Affected rows:'

,

result.

affectedRows

)

;

   

return

result

;

 

}

catch

(

err

)

{

    console.

error

(

'Update error:'

,

err

)

;

   

throw

err

;

 

}

}

Delete data (DELETE)

Example

async

function

deleteUser

(

id

)

{

 

try

{

   

const

[

result

]

=

await promisePool.

query

(

     

'DELETE FROM users WHERE id = ?'

,

     

[

id

]

   

)

;

    console.

log

(

'Deleted rows:'

,

result.

affectedRows

)

;

   

return

result

;

 

}

catch

(

err

)

{

    console.

error

(

'Delete error:'

,

err

)

;

   

throw

err

;

 

}

}


Advanced Features and Best Practices

Transaction processing

Example

async

function

transferFunds

(

fromId

,

toId

,

amount

)

{

  let connection

;

 

try

{

   

// Get a connection from the pool

    connection

=

await promisePool.

getConnection

(

)

;

   

   

// Start a transaction

    await connection.

beginTransaction

(

)

;

   

   

// Perform the transfer operation

    await connection.

query

(

     

'UPDATE accounts SET balance = balance - ? WHERE id = ?'

,

     

[

amount

,

fromId

]

   

)

;

   

    await connection.

query

(

     

'UPDATE accounts SET balance = balance + ? WHERE id = ?'

,

     

[

amount

,

toId

]

   

)

;

   

   

// Commit the transaction

    await connection.

commit

(

)

;

    console.

log

(

'Transfer successful'

)

;

 

}

catch

(

err

)

{

   

// Roll back on error

   

if

(

connection

)

await connection.

rollback

(

)

;

    console.

error

(

'Transfer failed:'

,

err

)

;

   

throw

err

;

 

}

finally

{

   

// Release the connection back to the pool

   

if

(

connection

)

connection.

release

(

)

;

 

}

}

Prepared statements

Prepared statements can improve performance and prevent SQL injection:

Example

async

function

getUserById

(

id

)

{

 

try

{

   

// Prepare a prepared statement

   

const

[

rows

]

=

await promisePool.

execute

(

     

'SELECT * FROM users WHERE id = ?'

,

     

[

id

]

   

)

;

   

return

rows

[

0

]

;

 

}

catch

(

err

)

{

    console.

error

(

'Query error:'

,

err

)

;

   

throw

err

;

 

}

}

Connection pool event listeners

Example

pool.

on

(

'connection'

,

(

connection

)

=>

{

  console.

log

(

'New connection established'

)

;

}

)

;

pool.

on

(

'acquire'

,

(

connection

)

=>

{

  console.

log

(

'Connection acquired'

)

;

}

)

;

pool.

on

(

'release'

,

(

connection

)

=>

{

  console.

log

(

'Connection released'

)

;

}

)

;

pool.

on

(

'enqueue'

,

(

)

=>

{

  console.

log

(

'Waiting for an available connection'

)

;

}

)

;


Error handling and debugging

Common error types

  1. Connection errors: Database server unreachable, authentication failure, etc.
  2. Query syntax errors: SQL statement errors
  3. Constraint violations: Such as duplicate primary keys, foreign key constraints, etc.
  4. Timeout errors: Query execution takes too long

Error handling strategies

Example

async

function

safeQuery

(

sql

,

params

)

{

 

try

{

   

const

[

rows

]

=

await promisePool.

query

(

sql

,

params

)

;

   

return

rows

;

 

}

catch

(

err

)

{

   

// Take different measures based on error type

   

switch

(

err.

code

)

{

     

case

'ER_DUP_ENTRY'

:

        console.

warn

(

'Duplicate entry:'

,

err.

sqlMessage

)

;

       

throw

new

Error

(

'Data already exists'

)

;

     

case

'ECONNREFUSED'

:

        console.

error

(

'Cannot connect to database'

)

;

       

throw

new

Error

(

'Service unavailable, please try again later'

)

;

     

default

:

        console.

error

(

'Database error:'

,

err

)

;

       

throw

err

;

   

}

 

}

}


Performance Optimization Suggestions

  1. Set the connection pool size appropriately: Usually 2-3 times the number of CPU cores
  2. Use a connection pool instead of a single connection: Especially in web applications
  3. Use indexes appropriately: Speed up query performance
  4. Batch Operations: Reduce round trips
  5. Using Prepared Statements: Improve performance of repeated queries
  6. Release resources regularly: Avoid connection leaks

Batch insert example:

Example

async

function

batchInsertUsers

(

users

)

{

 

const

values

=

users.

map

(

user

=>

[

user.

name

,

user.

email

]

)

;

 

 

try

{

   

const

[

result

]

=

await promisePool.

query

(

     

'INSERT INTO users (name, email) VALUES ?'

,

     

[

values

]

   

)

;

    console.

log

(

'Rows inserted:'

,

result.

affectedRows

)

;

   

return

result

;

 

}

catch

(

err

)

{

    console.

error

(

'Batch insert error:'

,

err

)

;

   

throw

err

;

 

}

}


Security considerations

  1. Never concatenate SQL strings: Use parameterized queries to prevent SQL injection
  2. Limit database user permissions: Application accounts only need necessary permissions
  3. Encrypt sensitive data: Passwords should be stored as salted hashes
  4. Use SSL connections: Encrypted connections are recommended in production
  5. Update dependencies regularly: Keep the mysql2 package up to date

Complete example project structure

project/

├── config/

│   └── db.js          # 数据库配置

├── models/

│   └── userModel.js   # 数据模型

├── services/

│   └── userService.js # 业务逻辑

├── app.js             # 主应用文件

└── package.json

db.js example:

Example

const

mysql

=

require

(

'mysql2'

)

;

const

pool

=

mysql.

createPool

(

{

  host

:

process.

env

.

DB_HOST

||

'localhost'

,

  user

:

process.

env

.

DB_USER

||

'root'

,

  password

:

process.

env

.

DB_PASSWORD

||

''

,

  database

:

process.

env

.

DB_NAME

||

'test_db'

,

  waitForConnections

:

true

,

  connectionLimit

:

10

,

  queueLimit

:

0

}

)

;

module.

exports

=

pool.

promise

(

)

;