node mysql insert,INSERT INTO失败,出现node-mysql

在尝试使用 Node.js 插入 MySQL 数据时遇到错误。问题出在 SQL 语句的构造上,使用了 `VALUES` 而不是 `SET`。正确的做法是使用 `SET` 关键字来设置要插入的字段值。例如:`INSERT INTO users SET ?`。修复此错误后,代码应能成功插入数据。
摘要由CSDN通过智能技术生成

I am trying to insert some data with node.js. I have written the following code and installed MySQL support via npm, but I failed to INSERT INTO the table.

Here is my code:

var mysql = require('mysql');

function BD() {

var connection = mysql.createConnection({

user: 'root',

password: '',

host: 'localhost',

port: 3306,

database: 'nodejs'

});

return connection;

}

app.post("/user/create", function(req, res) {

var objBD = BD();

var post = {

username: req.body.username,

password: req.body.password

};

objBD.query('INSERT INTO users VALUES ?', post, function(error) {

if (error) {

console.log(error.message);

} else {

console.log('success');

}

});

});

HTML code:

The error message is:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near .'username' = 'Test' , 'password' = 'test' at line 1

What is my mistake?

解决方案If you paid attention, you may have noticed that this escaping allows you to do neat things like this:

var post = {id: 1, title: 'Hello MySQL'};

var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {

// Neat!

});

console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

Notice that they use SET instead of VALUES. INSERT INTO ... SET x = y is a valid MySQL query, while INSERT INTO ... VALUES x = y is not.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值