📅  最后修改于: 2023-12-03 15:14:57.313000             🧑  作者: Mango
Express是一个基于Node.js平台的开放源代码Web应用程序框架。它使得在Node.js中使用数据库变得非常容易。在Express中,可以使用许多流行的关系型和非关系型数据库,如MySQL、PostgreSQL、MongoDB、Redis等。本文将介绍如何使用Express连接和操作这些数据库。
安装MySQL可以使用npm包mysql,该包提供了MySQL客户端用于Node.js。首先,需要在本地安装MySQL服务器,然后安装mysql包。
$ npm install mysql
使用mysql包连接MySQL非常容易。首先需要建立一个连接,然后可以执行各种SQL查询。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ' + err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
});
connection.end();
下面的代码演示了如何执行一个简单的查询。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ' + err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) throw error;
console.log(results);
});
});
connection.end();
插入记录也非常容易。下面的代码演示了如何插入一条新记录。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ' + err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
const user = { name: 'John', email: 'john@example.com' };
connection.query('INSERT INTO users SET ?', user, (error) => {
if (error) throw error;
console.log('New user inserted successfully!');
});
});
connection.end();
下面的代码演示了如何更新一条记录。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ' + err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
const user = { id: 1, name: 'John Doe', email: 'john@example.com' };
connection.query('UPDATE users SET ? WHERE id = ?', [user, user.id], (error) => {
if (error) throw error;
console.log('User updated successfully!');
});
});
connection.end();
下面的代码演示了如何删除一条记录。
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'database_name'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL: ' + err.stack);
return;
}
console.log('Connected to MySQL as id ' + connection.threadId);
const id = 1;
connection.query('DELETE FROM users WHERE id = ?', id, (error) => {
if (error) throw error;
console.log('User deleted successfully!');
});
});
connection.end();
安装PostgreSQL可以使用npm包pg,该包提供了PostgreSQL客户端用于Node.js。首先,需要在本地安装PostgreSQL服务器,然后安装pg包。
$ npm install pg
使用pg包连接PostgreSQL也非常容易。首先需要建立一个连接,然后可以执行各种SQL查询。
const { Client } = require('pg');
const client = new Client({
user: 'username',
password: 'password',
host: 'localhost',
port: 5432,
database: 'database_name'
});
client.connect((err) => {
if (err) {
console.error('Error connecting to PostgreSQL: ' + err.stack);
return;
}
console.log('Connected to PostgreSQL as id ' + client.processID);
});
client.end();
下面的代码演示了如何执行一个简单的查询。
const { Client } = require('pg');
const client = new Client({
user: 'username',
password: 'password',
host: 'localhost',
port: 5432,
database: 'database_name'
});
client.connect((err) => {
if (err) throw err;
client.query('SELECT * FROM users', (err, res) => {
if (err) throw err;
console.log(res.rows);
client.end();
});
});
插入记录也非常容易。下面的代码演示了如何插入一条新记录。
const { Client } = require('pg');
const client = new Client({
user: 'username',
password: 'password',
host: 'localhost',
port: 5432,
database: 'database_name'
});
client.connect((err) => {
if (err) throw err;
const user = { name: 'John', email: 'john@example.com' };
client.query('INSERT INTO users(name, email) VALUES($1, $2)', [user.name, user.email], (err) => {
if (err) throw err;
console.log('New user inserted successfully!');
client.end();
});
});
下面的代码演示了如何更新一条记录。
const { Client } = require('pg');
const client = new Client({
user: 'username',
password: 'password',
host: 'localhost',
port: 5432,
database: 'database_name'
});
client.connect((err) => {
if (err) throw err;
const user = { id: 1, name: 'John Doe', email: 'john@example.com' };
client.query('UPDATE users SET name = $1, email = $2 WHERE id = $3', [user.name, user.email, user.id], (err) => {
if (err) throw err;
console.log('User updated successfully!');
client.end();
});
});
下面的代码演示了如何删除一条记录。
const { Client } = require('pg');
const client = new Client({
user: 'username',
password: 'password',
host: 'localhost',
port: 5432,
database: 'database_name'
});
client.connect((err) => {
if (err) throw err;
const id = 1;
client.query('DELETE FROM users WHERE id = $1', [id], (err) => {
if (err) throw err;
console.log('User deleted successfully!');
client.end();
});
});
安装MongoDB可以使用npm包mongodb,该包提供了MongoDB客户端用于Node.js。首先,需要在本地安装MongoDB服务器,然后安装mongodb包。
$ npm install mongodb
使用mongodb包连接MongoDB也非常容易。首先需要建立一个连接,然后可以执行各种MogoDB操作。
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'database_name';
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect((err) => {
if (err) {
console.error('Error connecting to MongoDB: ' + err.stack);
return;
}
console.log('Connected to MongoDB as id ' + client.topology.s.state.sessionId);
const db = client.db(dbName);
client.close();
});
插入文档也非常容易。下面的代码演示了如何插入一条新文档。
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'database_name';
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect((err) => {
if (err) throw err;
const db = client.db(dbName);
const user = { name: 'John', email: 'john@example.com' };
db.collection('users').insertOne(user, (err) => {
if (err) throw err;
console.log('New user inserted successfully!');
client.close();
});
});
下面的代码演示了如何更新一条文档。
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'database_name';
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect((err) => {
if (err) throw err;
const db = client.db(dbName);
const query = { name: 'John' };
const newValues = { $set: { email: 'john@example.com' } };
db.collection('users').updateOne(query, newValues, (err) => {
if (err) throw err;
console.log('User updated successfully!');
client.close();
});
});
下面的代码演示了如何删除一条文档。
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const dbName = 'database_name';
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect((err) => {
if (err) throw err;
const db = client.db(dbName);
const query = { name: 'John' };
db.collection('users').deleteOne(query, (err) => {
if (err) throw err;
console.log('User deleted successfully!');
client.close();
});
});