Vincent
Vincent

Reputation: 2093

Nodejs mysql query not executing

I am trying to use node.js for the creation of a MySql database and tables.

The query I want to execute is:

CREATE DATABASE NodeTest;USE NodeTest;CREATE TABLE tblUsers (userId varchar(32), userName varchar(255), friendlyUserName varchar(255));

So I concatenate the queries together. In MySqlWorkbench this is working just fine.

In my NodeJS project it says there is a syntax error in my SQL statement.

My node code:

    mysqlConnection.query( 'CREATE DATABASE NodeTest;USE NodeTest;CREATE TABLE tblUsers (userId varchar(32), userName varchar(255), friendlyUserName varchar(255));' , function( oError ){

        if ( oError )  throw oError;

        console.log( 'Database created.' );
    });

I am using node-mysql (https://github.com/felixge/node-mysql) for my mysql operations.

According to the docs it is possible concatenate queries.

Why is this not working?

Upvotes: 2

Views: 4314

Answers (2)

Vincent
Vincent

Reputation: 2093

I hate to anwser my own questions, but I found the solution.

I miss red the documentation. It is possible by setting the option {multipleStatements: true} in your createConnection() options.

Like so:


    mysqlConnection = mysql.createConnection({
        host: settings.mysqlServer,
        user: settings.mysqlUser,
        password: settings.mysqlPassword,
        multipleStatements: true   // <------
    });

    mysqlConnection.query( 'CREATE DATABASE NodeTest;USE NodeTest;CREATE TABLE tblUsers (userId varchar(32), userName varchar(255), friendlyUserName varchar(255));' , function( oError ){

        if ( oError )  throw oError;

        console.log( 'Database created.' );
    });

Upvotes: 9

Jatin Raghav
Jatin Raghav

Reputation: 62

For create connection of node.js with MySQL first you install mysql connector in node.js with

$ npm install mysql

then You should add code in datasources.json file

{
  "db": {
    "name": "db",
    "connector": "memory"
  },
  "sql": {
    "host": "localhost",
    "port": "3306",
    "database": "database name",
    "username": "root",
    "password": "",
    "name": "sql",
    "connector": "mysql"
  }
}

for establish connection add code in .js file

module.exports = function(Module_Name) {

    Module_Name.remoteMethod( 'table_name',
    { accepts: [],
    returns: [
    {arg: 'data', type: 'string',}
    ],
    });

    Module_Name.table_name= function (cb) {

        var ds = Module_Name.dataSource;

        ds.connector.query(sql, function (err) {

            if (err) console.error(err);

        });
    };
};

Upvotes: -1

Related Questions