【问题标题】:Node.js and mysql. Insert into local databaseNode.js 和 mysql。插入本地数据库
【发布时间】:2021-03-30 13:25:52
【问题描述】:

我目前正在开发一个 html 表单,该表单允许用户输入他们的头衔、名字、姓氏、手机和电子邮件。目前,这些数据被推送到名为 userDatabase[] 的内存数据库中。

我希望能够将数据插入到我的本地 mysql 数据库中。我可以使用此代码毫无问题地连接到我的数据库。

var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "user",
password: "password",
database: "user",
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

在下面的代码中,您可以看到数据正在被推送到内存数据库中。

        if (currentMethod === "POST") {

            // read the body of the POST request
            request.on("data", function(chunk) {
                requestBody += chunk.toString();
            });

            // determine the POST request Content-type (and log to console)
            // Either: (i)  application/x-www-form-urlencoded or (ii) application/json
            const { headers } = request;
            let ctype = headers["content-type"];
            console.log("RECEIVED Content-Type: " + ctype + "\n");

            // finished reading the body of the request
            request.on("end", function() {
                var userData = "";
                // saving the user from the body to the database
                if (ctype.match(new RegExp('^application/x-www-form-urlencoded'))) {
                    userData = querystring.parse(requestBody);
                } else {
                    userData = JSON.parse(requestBody);
                }
                //**************** */
                userDatabase.push(userData)

我尝试将数据插入到名为“个人”的表中,如下所示:但我收到错误错误:ER_PARSE_ERROR:您的 SQL 语法有错误;查看与您的 MariaDB 服务器版本相对应的手册,了解在 'title = 'ms'、firstname = 'Tina'、surname = 'poole'、mobile = '+3 附近使用的正确语法。 ..' 在第 1 行

  con.query("INSERT INTO personal (title , firstname, surname, mobile , email ) VALUES ?", [userData], function(err, result) {
                    if (err) throw err;
                    console.log("1 record inserted");
                });

【问题讨论】:

    标签: mysql node.js


    【解决方案1】:

    您将 MySQL 的 INSERT 的两种不同语法模式混为一谈。在这些类型的情况下,您应该参考relevant documentation

    当指定 key='value' 对时,INSERT 的语法将符合以下格式:

    INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
        [INTO] tbl_name
        [PARTITION (partition_name [, partition_name] ...)]
        SET assignment_list
        [ON DUPLICATE KEY UPDATE assignment_list]
    

    这种格式与传统的INSERT INTO tbl_name (fieldnames) VALUES (values) 有明显的区别,因为它既不需要字段名称也不需要VALUES 关键字,正如您在上面的查询语法中包含的那样。相反,您将包含 SET <assignment_list> 序列,它在语法上与传统的 UPDATE 查询类似。

    相反,您的代码将类似于以下内容:

    con.query("INSERT INTO personal SET ?", [userData], function(err, result) {
        if (err) throw err;
        console.log("1 record inserted");
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-06
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多