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

六、前端请求接口

相关推荐
roman_日积跬步-终至千里36 分钟前
【资源控制】自助查询的智能路由
java·大数据·数据库
SelectDB37 分钟前
无锡锡商银行 数据仓库演进:Apache Doris / SelectDB 的技术能力与实践
数据库
SelectDB1 小时前
雨润集团 统一实时数据仓库:Apache Doris / SelectDB 的技术能力与实践
数据库
SelectDB1 小时前
天翼云 Iceberg 湖仓一体:Apache Doris / SelectDB 的技术能力与实践
数据库
l1258651 小时前
# RAG重排序实战:硅基流动bge-reranker-v2-m3在线API vs 本地CrossEncoder,一篇讲透两种方案
数据库·人工智能·python·深度学习·算法·机器学习·langchain
张洛闻Eren2 小时前
MySQL 管理复制拓扑【MySQL第四课】
linux·运维·数据库·mysql
西安景驰电子2 小时前
《PTP精确时间协议系列》第二篇:工程部署、调试与性能优化
运维·服务器·网络·数据库·windows·性能优化
xrkhy2 小时前
redis-shake的使用windows版本
数据库·windows·redis
小王C语言3 小时前
MySQL 内置函数:日期函数、字符串函数、数学函数、其他函数
数据库·mysql
ClouGence4 小时前
当 AI 开始直接操作数据库,传统数据库管理工具还有必要吗?
数据库·后端·agent