express连接mysql

一、 安装express

bash 复制代码
npm install express --save

二、express配置

bash 复制代码
//引入
const express = require("express");
//创建实例
const app = express();
//启动服务
app.listen(8081, () => {
  console.log("http://localhost:8081");
});

三、安装mysql

bash 复制代码
npm i mysql

四、配置到express中

bash 复制代码
const express = require("express");
const mysql = require("mysql"); //引入mysql
const app = express();
// 设置MySQL连接配置
const connection = mysql.createConnection({
  host: "localhost", 
  user: "root",  //数据库账号
  password: "root", //数据库密码
  database: "deli", //数据库名称
});
// 连接到MySQL数据库
connection.connect((error) => {
  if (error) throw error;
  //连接成功打印结果`如果连接失败,记得查看数据库是否开启`
  console.log("Successfully connected to the database.");
});
app.listen(8081, () => {
  console.log("http://localhost:8081");
});

五、加入get请求

bash 复制代码
const express = require("express");
const mysql = require("mysql");
const app = express();
// 设置MySQL连接配置
const connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "root",
  database: "deli",
});
// 连接到MySQL数据库
connection.connect((error) => {
  if (error) throw error;
  console.log("Successfully connected to the database.");
});


`这里为增加的get请求内容`
app.get("/testApi", (req, res) => {
  //获取到请求参数
  const { config_name } = req.query;
  //去表名称为config的表中去查数据 ,查询条件为`config_name="${config_name}"`,其中双引号不可省去
  connection.query(
    `SELECT * FROM config  where config_name="${config_name}"`,
    (error, results, fields) => {
      if (error) throw error;
      // 发送响应
      res.send(results);
    }
  );
});

app.listen(8081, () => {
  console.log("http://localhost:8081");
});

六、前端请求接口

相关推荐
Austindatabases8 分钟前
DBA 从“修电脑的” 到 上演一套 “数据治理” 大戏 --- 维护DBA生存空间,体现个体价值
数据库·dba
LB211217 分钟前
Redis黑马点评 day01
数据库·redis·缓存
白小筠25 分钟前
创建Django项目
数据库·django·sqlite
扑克中的黑桃A2 小时前
金仓多模数据库平替MongoDB的电子证照国产化实践——从2TB数据迁移到1600+并发支撑
数据库
计算机毕业设计小帅2 小时前
【2026计算机毕业设计】基于Django的社区婴幼儿预防接种系统
数据库·django·课程设计
友友马2 小时前
『 数据库 』MySQL复习 - 内置函数详解
数据库·mysql
ANYOLY2 小时前
慢查询优化
mysql
互联网中的一颗神经元3 小时前
小白python入门 - 6. Python 分支结构——逻辑决策的核心机制
开发语言·数据库·python
数据库知识分享者小北4 小时前
AI Agent的未来之争:任务规划,该由人主导还是AI自主?——阿里云RDS AI助手的最佳实践
数据库·阿里云·数据库rds
凸头4 小时前
MySQL 的四种 Binlog 日志处理工具:Canal、Maxwell、Databus和 阿里云 DTS
数据库·mysql·阿里云