INSERT INTO fails with node-mysql

故事扮演 提交于 2019-11-27 15:00:52

Pay attention to the documentation of node-mysql:

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.

I know this is an old post but thought I'd share that INSERT INTO...VALUES is a valid command (no SET) and very useful for bulk updates:

db.query('INSERT INTO myTable (field1, field2, field3) VALUES ?', [values])

where [values] is an array of arrays, each array containing those three fields and inserted as a record in the table.

For others searching, I had this same issue, but it turns out it was a more complicated, unrelated issue. I wasn't declaring 'use strict'; at the very top of the document.

I know this in itself won't solve the database insert problem, but it pointed out parts of my entire script that were coded incorrectly, and once fixing those, it worked as expected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!