Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Connecting to MySQL
interview

Q1. How do you connect Node.js to MySQL?
Use the mysql2 package. Install: npm install mysql2. Create connection pool:
const mysql = require('mysql2'); const pool = mysql.createPool({ host: 'localhost', user: 'root', password: 'password', database: 'mydb', waitForConnections: true, connectionLimit: 10 });
Use pool.promise() for async/await.

Q2. What's the difference between mysql and mysql2 packages?
mysql2 is a fork of mysql with better performance, promise support, prepared statements, and more features. It's the recommended choice for new projects. mysql2 supports both callbacks and promises (via .promise()), while the original mysql package requires callbacks or manual promisification.

Q3. How do you execute queries with mysql2?
With promises:
const [rows, fields] = await pool.promise().query('SELECT * FROM users WHERE id = ?', [userId]);
For single row: const [rows] = await pool.promise().query(...);. Always use placeholders (?) to prevent SQL injection. For transactions, get a connection from the pool and use beginTransaction, commit, rollback.

Q4. How do you handle connection errors with MySQL?
Use try/catch around queries. For connection errors, the pool will handle reconnection automatically. Listen for error events:
pool.on('error', (err) => { console.error('Pool error', err); });
. When getting a connection, handle errors:
pool.getConnection((err, connection) => { if (err) throw err; });

Q5. How do you use ORMs like Sequelize with MySQL?
Sequelize is a popular ORM for SQL databases. Install: npm install sequelize mysql2. Define models:
const User = sequelize.define('User', { name: DataTypes.STRING, email: DataTypes.STRING });
Then sync with database. ORMs provide higher-level abstractions, associations, and validations but add complexity.