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) {
});
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.
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.
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'
});
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) {
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With