Inserting Data with Node.js

Onder OZCAN picture Onder OZCAN · Aug 13, 2013 · Viewed 61.8k times · Source

I 'am trying to insert some data with Node.js. I installed mysql support with npm . I just checked arround some source code, I've wrote following code , I can follow sql output in console.log and SQL output is correct. But It does not affect on any rows in mySQL database.

Here is my code :

var mysql      = require('mysql');

var connection = mysql.createConnection({
  host     : 'cccc.net',
  user     : 'username',
  password : 'password',
});

var post  = {srcUserID: userSrcID, destUserID: msg.userid, messageContent: msg.txt, messageSendDate:sendDate };

connection.query('INSERT INTO messages VALUES ?', post, function(err, result) {

});

Answer

user254153 picture user254153 · Jul 2, 2015

Its to late but If this can help other.

 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 INSET INTO ... VALUES x = y is not.