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");
});

六、前端请求接口

相关推荐
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
Java水解1 天前
Mysql查看执行计划、explain关键字详解(超详细)
后端·mysql
知其然亦知其所以然1 天前
MySQL 社招必考题:如何优化查询过程中的数据访问?
后端·mysql·面试
DemonAvenger1 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
程序新视界1 天前
如何在MySQL中创建聚集索引?
mysql
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
程序新视界2 天前
学习MySQL绕不开的两个基础概念:聚集索引与非聚集索引
mysql
RestCloud2 天前
跨境数据传输:ETL如何处理时区与日期格式差异
mysql·api