Connections and First Steps in Databases
Connecting to a database is one of the first steps to interact with the data it stores. Both SQL and NoSQL databases have their own ways of connecting and performing queries. Below, we will see how to connect to each type of database and execute some basic operations.
Connecting to an SQL Database
To connect to an SQL database, you can use libraries like `mysql` for MySQL, `pg` for PostgreSQL, or `sqlite3` for SQLite in JavaScript. Below is a basic example using Node.js and MySQL:
// Install the mysql package // npm install mysql const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'your_password', database: 'database_name' }); connection.connect((err) => { if (err) throw err; console.log('Connected to the database!'); }); // Perform a query connection.query('SELECT * FROM table_name', (err, results) => { if (err) throw err; console.log(results); }); connection.end();
Connecting to a NoSQL Database
To connect to a NoSQL database like MongoDB, you can use the `mongoose` library or the native MongoDB driver. Here is an example using `mongoose`:
// Install the mongoose package // npm install mongoose const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/database_name', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => { console.log('Connected to MongoDB!'); }).catch(err => { console.error('Connection error:', err); }); // Define a model const User = mongoose.model('User', new mongoose.Schema({ name: String, age: Number })); // Create a new user const newUser = new User({ name: 'John', age: 25 }); newUser.save().then(() => console.log('User saved!')).catch(err => console.error(err));
First Steps with Queries
Once the connection is established, you can perform basic queries to manipulate data. Below are examples of common queries for both databases.
SQL Queries
- Select data: `SELECT * FROM table_name;`
- Insert data: `INSERT INTO table_name (column1, column2) VALUES (value1, value2);`
- Update data: `UPDATE table_name SET column1 = value1 WHERE condition;`
- Delete data: `DELETE FROM table_name WHERE condition;`
NoSQL Queries (MongoDB)
- Select data:
User.find({});
- Insert data:
User.create({ name: 'John', age: 25 });
- Update data:
User.updateOne({ name: 'John' }, { $set: { age: 26 } });
- Delete data:
User.deleteOne({ name: 'John' });
Conclusion
Connecting to a database and performing basic queries are fundamental skills for any developer working with data. Whether using SQL or NoSQL, understanding how to interact with databases will allow you to build more robust and efficient applications.
Exercises
Interactive Test 1: Drag and Drop.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Fill in the Blanks
Rellena los huecos en cada casilla.
const express = require(''); const mongoose = require(''); const app = express(); const PORT = process.env.PORT || 3000; mongoose.connect('', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Connected to MongoDB')) .catch(err => console.error('Could not connect to MongoDB', err)); app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
Practical Exercise:
Statement:
Here's an example of how to connect to MongoDB and create a basic server using Express.