数据层-3-将JSON格式的文件的数据批量插入到数据库当中

将JSON格式的文件数据批量插入到数据库中

##项目所在地址

https://github.com/zhou-X-boy/Vue_study/tree/master/VueProject/pdd

在服务端server文件夹下的router文件夹下的index.js文件中操作

index.js

pdd\server\router\index.js

index.js

const express = require('express');
const router = express.Router();

//引入连接的mysql的模块
const conn = require('./../db/db');

//批量将JSON格式的数据插入到数据库当中
//1:获取到需要批量插入的JSON文件中的数据
const recommendArr = require('./../data/recommend').data;
router.get('/recommend/api', function (req, res, next) {
  // 1. 定义临时数组
  let temp_arr_all = [];
  // 2. 遍历获取到的JSON文件获取到的数据
  for (let i = 0; i < recommendArr.length; i++) {
    // 2.1 取出该数据中的单个数据对象
    let oldItem = recommendArr[i];
    // 2.2 取出跟数据库表中对应的需要插入的数据的字段
    let temp_arr = [];
    temp_arr.push(oldItem.goods_id);
    temp_arr.push(oldItem.goods_name);
    temp_arr.push(oldItem.short_name);
    temp_arr.push(oldItem.thumb_url);
    temp_arr.push(oldItem.hd_thumb_url);
    temp_arr.push(oldItem.image_url);
    temp_arr.push(oldItem.price);
    temp_arr.push(oldItem.normal_price);
    temp_arr.push(oldItem.market_price);
    temp_arr.push(oldItem.sales_tip);
    temp_arr.push(oldItem.hd_url);
    // 2.3 合并到定义的临时的数组中
    temp_arr_all.push(temp_arr);
  }
  // console.log(temp_arr_all);

  // 3. 批量插入数据库表
  // 3.1 数据库查询的语句
  let sqlStr = "INSERT INTO pdd_recommend(goods_id,goods_name,short_name,thumb_url,hd_thumb_url,image_url,price,normal_price,market_price,sales_tip,hd_url) VALUES ?";
  // 3.2 执行语句
  conn.query(sqlStr, [temp_arr_all], (error, results, fields) => {
    if (error) {
      console.log(error);
      console.log('插入失败');
    } else {
      console.log('插入成功');
    }
  });
});

重启服务端后,才浏览器输入 http://localhost:3000/recommend/api 查看控制台输出结果

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值