Node.js是一种在服务器端运行JavaScript的开发平台,可以使用它来进行增删改查操作。常见的数据库有MySQL、MongoDB、PostgreSQL等。下面分别介绍在这些数据库中如何进行增删改查操作:

  1. MySQL

在Node.js中,可以使用mysql模块来连接MySQL数据库。下面是一个示例代码,实现了插入、查询、更新和删除操作:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'test'
});

// 插入数据
connection.query('INSERT INTO users SET ?', { username: 'test', password: '123456' }, (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

// 查询数据
connection.query('SELECT * FROM users', (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

// 更新数据
connection.query('UPDATE users SET password = ? WHERE username = ?', ['654321', 'test'], (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

// 删除数据
connection.query('DELETE FROM users WHERE username = ?', ['test'], (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

connection.end();
  1. MongoDB

在Node.js中,可以使用mongoose模块来连接MongoDB数据库。下面是一个示例代码,实现了插入、查询、更新和删除操作:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true });

const userSchema = new mongoose.Schema({
  username: String,
  password: String
});

const User = mongoose.model('User', userSchema);

// 插入数据
const user = new User({ username: 'test', password: '123456' });
user.save((error, result) => {
  if (error) throw error;
  console.log(result);
});

// 查询数据
User.find((error, result) => {
  if (error) throw error;
  console.log(result);
});

// 更新数据
User.updateOne({ username: 'test' }, { password: '654321' }, (error, result) => {
  if (error) throw error;
  console.log(result);
});

// 删除数据
User.deleteOne({ username: 'test' }, (error, result) => {
  if (error) throw error;
  console.log(result);
});

mongoose.disconnect();
  1. PostgreSQL

在Node.js中,可以使用pg模块来连接PostgreSQL数据库。下面是一个示例代码,实现了插入、查询、更新和删除操作:

const { Pool } = require('pg');

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'test',
  password: 'password',
  port: 5432
});

// 插入数据
pool.query('INSERT INTO users (username, password) VALUES ($1, $2)', ['test', '123456'], (error, result) => {
  if (error) throw error;
  console.log(result);
});

// 查询数据
pool.query('SELECT * FROM users', (error, result) => {
  if (error) throw error;
  console.log(result.rows);
});

// 更新数据
pool.query('UPDATE users SET password = $1 WHERE username = $2', ['654321', 'test'], (error, result) => {
  if (error) throw error;
  console.log(result);
});

// 删除数据
pool.query('DELETE FROM users WHERE username = $1', ['test'], (error, result) => {
  if (error) throw error;
  console.log(result);
});

pool.end();
nodejs 增删改查

原文地址: https://www.cveoy.top/t/topic/Yyz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录