【问题标题】:How to send an array from an HTML page to Node.js and then store it on a database [closed]如何将数组从 HTML 页面发送到 Node.js,然后将其存储在数据库中 [关闭]
【发布时间】:2019-05-02 01:49:13
【问题描述】:

我需要帮助转移一个用 javascript 制作的数组。我对如何使用 node.js 然后将其发送到 MySql 感到困惑。任何指向有用视频或解释的链接将不胜感激。谢谢

【问题讨论】:

  • 阅读使用 ajax
  • 我有代码,但我从未使用过 node.js。我在谷歌上找到的大多数视频都使用不同的语言。

标签: javascript html mysql node.js mysql-workbench


【解决方案1】:

我建议通过useful tutorials 阅读一下。

也就是说,执行此操作的基本方法是使用像 MYSQL2 这样的 NPM 包。然后循环遍历数组以创建插入语句:

// get the client
const mysql = require('mysql2');
 
// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

/*
Assuming your database has a table named `employee` with a two columns: id and name.

Goal: INSERT INTO employee(id,name)
VALUES 
   (1,"Jerry"),
   (2,"Jenny"),
   (3,"Jessie"); */
   
var ary=[{id: 1, name: "Jerry"}, {id: 2, name:"Jenny"}, {id: 3, name: "Jessie"}];
var values = ary.map(a => {
  return `(${a.id}, ${a.name})`;
});

// simple query
connection.query(
  'INSERT INTO employee(id, name) VALUES ' + values.join(','),
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

【讨论】:

  • 谢谢,我知道它现在是如何工作的了。我会阅读您的答案所附的教程。
猜你喜欢
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 2016-06-02
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多