Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting Data with Node.js

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) {

});
like image 220
Onder OZCAN Avatar asked Aug 13 '13 14:08

Onder OZCAN


People also ask

How do you insert data into a table?

To insert records into a table, enter the key words insert into followed by the table name, followed by an open parenthesis, followed by a list of column names separated by commas, followed by a closing parenthesis, followed by the keyword values, followed by the list of values enclosed in parenthesis.

How do you add data to a database?

Simple INSERT statement to add data to the table. Use INSERT Statement to add multiple rows in the table. INSERT INTO SELECT clause to insert the output generated by the SELECT query. INSERT IGNORE clause to ignore the error generated during the execution of the query.


2 Answers

You have to select a DB before performing a query. The easiest way is to add it to the object in the createConnection call:

var connection = mysql.createConnection({
  host     : 'cccc.net',
  user     : 'xxxxx_usr',
  password : 'xxxxxxx',
  database : 'database_name'
});
like image 199
SheetJS Avatar answered Oct 09 '22 09:10

SheetJS


As you've pointed out from your comments, you had no database selected:

ER_NO_DB_ERROR: No database selected

Hence, you need to select a database first, and then it works as expected. What you need to add is the database property to your call to createConnection, so your code should look like the following:

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'cccc.net',
  user: 'xxxxx_usr',
  password: 'xxxxxxx',
  database: 'name of your database goes here …'
});

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

connection.query('INSERT INTO messages VALUES ?', post, function (err, result) {
  // ...
});
like image 41
Golo Roden Avatar answered Oct 09 '22 08:10

Golo Roden