后端连接MySQL数据库

436 阅读1分钟

1 安装 npm install mysql2 -S

2 创建文件/db/sql.js 连接数据库

const mysql = require("mysql");
let connection = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "wh20000805",
  database: "vue-store",
});
module.exports = connection;

3 使用

//查询商品数据接口
router.get("/api/goods/shopList", function (req, res, next) {
  //前端给后端的数据
  let [searchName, orderName] = Object.keys(req.query);
  let [name, order] = Object.values(req.query);
  
  //查询
  connection.query(
    'select * from goods_list where name like "%' +
      name +
      '%" order by ' +
      orderName +
      " " +
      order +
      "",
    (error, results) => {
      res.send({
        code: 0,
        data: results,
      });
    }
  );
});