In the world of modern web development, seamless and secure interaction with databases is the cornerstone of any successful application. MySQL stands as one of the most popular relational database management systems, while the Node.js environment provides the speed and efficiency needed for server-side data processing.
This detailed guide will walk you step-by-step through how to connect your Node.js application to a MySQL database, from setting up the environment to executing complex queries and securing your application.
Before diving into writing code, you must ensure your development environment is fully prepared. This project requires three essential components:
node -v
in your command line.npm install mysql
Once your environment is ready, the next logical step is to create an effective connection between your Node.js application and the MySQL database. No queries can be executed until this step is successfully completed. The connection requires basic information such as the host, username, password, and database name.
Example of Creating a Connection:
const mysql = require('mysql');
// Create a connection object with database credentials
const connection = mysql.createConnection({
host: "localhost",
user: "your_username", // Replace with your username
password: "your_password", // Replace with your password
database: "your_database_name" // Replace with your database name
});
// Attempt to connect
connection.connect(function(err) {
if (err) {
console.error('Error connecting: ' + err.stack);
return;
}
console.log('Successfully connected. Connection ID is ' + connection.threadId);
});
After establishing the connection, you can begin performing basic operations on your data.
To insert new records into a table, we use the INSERT INTO
query. You can retrieve the ID of the newly added row from the result
object.
const sql = "INSERT INTO customers (name, address) VALUES ('John Doe', '123 Main St')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(`1 record inserted successfully, ID: ${result.insertId}`);
});
The SELECT
query is used to fetch data from a table. You can specify certain columns or retrieve all data using *
.
// Fetch all records from the customers table
connection.query("SELECT * FROM customers", function (err, results, fields) {
if (err) throw err;
console.log('Data retrieved:', results);
});
You can also customize your query by using a WHERE
clause to filter results based on a specific condition, or ORDER BY
to sort them.
// Fetch customers living at a specific address and order them by name
const addressQuery = "SELECT * FROM customers WHERE address = ? ORDER BY name ASC";
connection.query(addressQuery, ['123 Main St'], function (err, results) {
if (err) throw err;
console.log('Custom search results:', results);
});
To modify an existing record, we use the UPDATE
query with a WHERE
clause to specify the record to be updated.
const updateSql = "UPDATE customers SET address = '456 Oak Ave' WHERE name = 'John Doe'";
connection.query(updateSql, function (err, result) {
if (err) throw err;
console.log(`${result.affectedRows} record(s) updated successfully.`);
});
To delete a record from a table, we use the DELETE
query with a WHERE
clause.
const deleteSql = "DELETE FROM customers WHERE name = 'John Doe'";
connection.query(deleteSql, function (err, result) {
if (err) throw err;
console.log(`${result.affectedRows} record(s) deleted successfully.`);
});
Application security is a top priority. SQL Injection is one of the most common security vulnerabilities targeting databases. These attacks occur when an attacker manages to insert or "inject" malicious SQL commands into your queries.
To prevent these vulnerabilities, you must always sanitize user-provided input before using it in queries. The mysql
library provides a secure way to pass values using question mark (?
) placeholders, which automatically escape any dangerous characters.
Insecure Method (Do Not Use):
const unsafeAddress = "456 Oak Ave' OR '1'='1";
const unsafeSql = "SELECT * FROM customers WHERE address = '" + unsafeAddress + "'";
// This query is vulnerable to injection!
Secure Method (Recommended):
const safeAddress = "456 Oak Ave";
const secureSql = "SELECT * FROM customers WHERE address = ?";
connection.query(secureSql, [safeAddress], function (err, result) {
if (err) throw err;
console.log(result);
});
For more information on how to protect against these attacks, you can review the SQL Injection Prevention Cheat Sheet from the OWASP Foundation.
In this guide, we have covered how to connect Node.js applications to MySQL databases, perform basic operations, and secure your queries. By mastering these skills, you are now able to build powerful and integrated web applications that manage data efficiently and securely. The next step is to explore more advanced concepts like Connection Pooling to improve performance and using ORM libraries like Sequelize or TypeORM to simplify database interactions in larger projects.