当前位置: 技术文章>> 详细介绍nodejs中的Express框架操作MySQL数据库

文章标题:详细介绍nodejs中的Express框架操作MySQL数据库
  • 文章分类: 后端
  • 10773 阅读
文章标签: nodejs javascript

在Node.js中,可以使用Express框架与MySQL数据库进行交互。下面是一个简单的示例代码,演示如何使用Express框架操作MySQL数据库:

  1. 安装MySQL模块和Express模块

首先,需要在Node.js项目中安装MySQL模块和Express模块,可以通过npm进行安装:


npm install mysql express
  1. 引入MySQL模块和Express模块

在Node.js中操作MySQL数据库需要使用require('mysql')模块,而Express框架则可以使用require('express')模块。例如:


const mysql = require('mysql');

const express = require('express');
  1. 创建Express应用程序并连接MySQL数据库

在Express应用程序中,可以通过调用mysql.createConnection()方法来创建与MySQL数据库的连接。例如:


const app = express();

const connection = mysql.createConnection({

host: 'localhost',

user: 'root',

password: 'password',

database: 'mydatabase'  

});
  1. 查询数据

在Express应用程序中,可以使用mysql.query()方法来执行SQL查询语句。例如:


app.get('/users', function (req, res) {

const sql = 'SELECT * FROM users';

connection.query(sql, function (error, results, fields) {

if (error) throw error;

res.json(results);

});

});
  1. 插入数据

在Express应用程序中,可以使用mysql.query()方法来执行SQL插入语句。例如:


app.post('/users', function (req, res) {

const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';

const values = [req.body.name, req.body.email];

connection.query(sql, values, function (error, results, fields) {

if (error) throw error;

res.json(results);

});

});
  1. 更新数据

在Express应用程序中,可以使用mysql.query()方法来执行SQL更新语句。例如:


app.put('/users/:id', function (req, res) {

const sql = 'UPDATE users SET name = ? WHERE id = ?';

const values = [req.body.name, req.params.id];

connection.query(sql, values, function (error, results, fields) {

if (error) throw error;

res.json(results);

});

});


推荐文章