So far, our JavaScript code runs in the browser and forgets everything when the page closes. To build powerful web applications that remember information (like user accounts, product lists, or blog posts), we need **databases**!
Databases are organized collections of data. Think of them as super-smart filing cabinets for your application's information.
Server-Side JavaScript with Node.js
While browser JavaScript is great for interactivity, it can't directly talk to databases for security reasons. This is where **Node.js** comes in! Node.js allows you to run JavaScript code on a server, which *can* securely connect to and manage databases.
When you build a full web application, your browser-side JavaScript sends requests to your Node.js server, and the Node.js server then talks to the database.
Types of Databases
- Relational Databases (SQL): Store data in structured tables with rows and columns, much like a spreadsheet. They use SQL (Structured Query Language) to interact with data.
Examples: MySQL, PostgreSQL, SQLite.
- NoSQL Databases: Offer more flexible data models, often without strict table schemas. Great for large amounts of unstructured or semi-structured data.
Examples: MongoDB (document-based), Cassandra (column-family), Redis (key-value).
Connecting to MySQL (Conceptual Example)
To connect Node.js to a MySQL database, you'd typically use a library (like the `mysql2` package). Here's a simplified conceptual example of how it works:
// This code runs on a Node.js server, not directly in the browser!
// First, you'd install a package: npm install mysql2
// Then, you'd import it:
// const mysql = require('mysql2/promise'); // Using promise-based version
async function connectAndQuery() {
try {
// 1. Establish a connection to the database
const connection = await mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database_name'
});
console.log('Connected to MySQL database!');
// 2. Execute a query (e.g., fetch all users)
const [rows, fields] = await connection.execute('SELECT * FROM users');
console.log('Users:', rows);
// 3. Insert new data
const [result] = await connection.execute(
'INSERT INTO users (name, email) VALUES (?, ?)',
['Jane Doe', 'jane@example.com']
);
console.log(`Inserted user with ID: ${result.insertId}`);
// 4. Close the connection
await connection.end();
console.log('Connection closed.');
} catch (error) {
console.error('Database error:', error);
}
}
// Call the function to run the database operations
// connectAndQuery();
This example demonstrates the basic **CRUD** operations (Create, Read, Update, Delete) that you perform with databases:
- Create: Adding new data (e.g., `INSERT`).
- Read: Retrieving data (e.g., `SELECT`).
- Update: Modifying existing data (e.g., `UPDATE`).
- Delete: Removing data (e.g., `DELETE`).
Learning database integration is a huge step towards building full-fledged, dynamic web applications!