← Back to Node.js Course | Chapter 9: Database Integration | Lesson 1 of 7

Connecting to MySQL

The mysql2 package connects your Node app to a MySQL database and runs queries.

In this page:

  1. Connecting to MySQL
Syntax
javascript
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection({
  host: 'host', user: 'user', password: 'password', database: 'database'
});
const [rows] = await connection.execute('SELECT * FROM table_name WHERE column = ?', [value]);

Connecting to MySQL

Install mysql2, create a connection or pool with host, user, password and database, then call query or execute. Use placeholders (?) with execute to avoid SQL injection. Always close connections or use a pool.

Note: Prepared statements with ? placeholders prevent SQL injection.

Example: Connecting to MySQL

bash
$ npm install mysql2
const mysql = require("mysql2/promise");
const pool = mysql.createPool({ host: "localhost", user: "app", password: process.env.DB_PASS, database: "shop" });
const [rows] = await pool.execute("SELECT id, name FROM users WHERE id = ?", [1]);
console.log(rows[0]);

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Building SQL with string concatenation
  2. Not closing connections
  3. Hard-coding credentials
Chapter Summary
  • Install mysql2
  • Create a pool
  • Use placeholders
  • Close or reuse connections
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.