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

});

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'
});

Node.js MySQL Insert Into, INSERT INTO customers (name, address) VALUES ? Example. Fill the "​customers" table with data: var mysql = require('mysql'); Node.js – MySQL Insert Data SQL uses following INSERT statement to insert data in tables. INSERT INTO users (user_id, user_name, email) VALUES (1, 'john', 'john@example.com')

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.

Inserting Data with Node.js, 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. Node.js MongoDB Insert. Insert Into Collection. To insert a record, or document as it is called in MongoDB, into a collection, we use the insertOne() method. The first parameter of the insertOne() method is an object containing the name(s) and value(s) of each field in the document you want to insert.

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) {
  // ...
});

Inserting Data Into an SQLite Table from a Node.js Application, Inserting Data Into an SQLite Table from a Node.js Application. Summary: in this tutorial, you will learn how to insert one or more row into an  To insert data into an SQLite table from a Node.js application, you follow these steps: Open a database connection. Execute an INSERT statement. Close the database connection.

   const pgp = require('pg-promise')()

// const connection = { host: 'localhost', port: 5432, db: 'users' }
const connection = process.env.NODE_ENV === 'test'
  ? 'postgres:///users_test'
  : 'postgres:///users'
const db = pgp(connection) 

const addUser = (userName, jobName) => {
      return db.one(`
            SELECT j.job_id
            FROM jobs AS s
            WHERE j.job_name = $1`
            , [jobName])
            .then((jobs) => {
        return db.one(`
            INSERT INTO users
            (name, job_id)
            VALUES ($1, $2)
            RETURNING user_id`,
          [userName, jobs.job_id])
    })
    }


     addUser('Micheal', 'teacher')
      .then(console.log)
      .catch(console.error)




      const addUserToCompany = (userName, companyName) => {
        let userId
        let companyId
        return db.one(`
          SELECT user_id
          FROM users
          WHERE name=$1`, [userName])
          .then((user) => {
            userId = user.user_id
            return db.one(`
            SELECT company_id
            FROM companies
            WHERE name=$1`, [companyName])
          })
          .then((company) => {
            ownerId = company.company_id
            return db.one(`
              INSERT INTO companyUsers
                (user_id, company_id)
              VALUES
                ($1, $2)
              RETURNING *`,
              [userId, companyId])
          })
      }
      addUserToCompany('Micheal', 'Code Academy')
        .then(console.log)
        .catch(console.error)



        const updateUserName = (userId, newName) => {
          db.oneOrNone('UPDATE users SET name=$1 WHERE user_id=$2 RETURNING user_id', [newName, userId])
            .then((returnedId) => {
              if (returnedId) return { success: true, message: '' }
              return { success: false, message: `Could not find userId ${userId}` }
            })
            .catch(err => Object({ success: false, message: err.message }))
    }
    updateUserName(17, 'Micheal-Moore')

module.exports = { addUser, addUserToCompany , updateUserName }

Node.js MySQL INSERT INTO Query Examples, Node.js MySQL INSERT INTO Query - Examples - In this tutorial, learn to insert is : connection.query(INSERT INTO TABLE (COLUMN1,COLUMN2) VALUES ? Node.js MySQL MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert Into MySQL Select From MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join Node.js MongoDB

Node.js MySQL Insert Record, Insert records in "employees" table. Create a js file named "insert" in DBexample folder and put the following data into it:. Summary: in this tutorial, you will learn how to insert one or more rows into a table from the node.js application. To insert a new row into a table, you follow these steps: Connect to the MySQL database.. Execute an INSERT statement by calling the query() method on a connection object. Close the database connection.

Node.JS INSERT QUERY How to add Data in MySQL Database , You can also insert multiple records into the database table. Create a JavaScript file in your application to insert data to table using Node.js  To insert a single document using MongoDB Compass: Navigate to the collection you wish to insert the document into: In the left-hand MongoDB Compass navigation pane, click the database to which your target collection belongs. From the database view, click the target collection name. Click the Insert Document button:

Node.js - MySQL Insert Data, If, for example, you need dynamic table creation, or real-time inserts, then I'll explain how to use the module to connect to a MySQL database and to a MySQL database from Node.js, let's see how to execute SQL queries. Once you have MySQL up and running on your computer, you can access it by using Node.js. To access a MySQL database with Node.js, you need a MySQL driver. This tutorial will use the "mysql" module, downloaded from NPM. To download and install the "mysql" module, open the Command Terminal and execute the following:

Comments
  • I think I've found my problem :D Error: ER_NO_DB_ERROR: No database selected
  • If that worked, then either delete the question or answer and accept it
  • Now it's working just fine ! thank you :)
  • Note that VALUES is not valid in MySQL use SET
  • Please don't just copy and paste answers from elsewhere stackoverflow.com/questions/21779528/…