[英]Node.js and mysql. Insert into local database
我目前正在研究 html 表单,该表单允许用户输入他们的头衔、名字、姓氏、手机和 email。 目前,这些数据被推送到名为 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 服务器版本相对应的手册,了解在第 1 行的“ title
= 'ms', firstname
= 'Tina', surname
= 'poole', mobile
= '+3...' 附近使用的正确语法
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 的INSERT
的两种不同的语法模式混为一谈。 在这些类型的情况下,您应该参考相关文档。
指定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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.