0

I want to create a manager to interact with mysql, but I'm not able to bring it into the main program. I'm mainly just trying to get the hang of javascript for this stuff (java, c background).

I have two files called main.js and MSYQLConnector.js. I want to use MYSQLConnector from

main.js

var root = __dirname, express = require('express');
var app = express();
var sql = require('./DBConnectors/MYSQLConnector.js');
var a = sql.sqlTest;//????? fail....

MYSQLConnector.js

var sqlTest = function (){
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : 'xxxx'
    });

    connection.connect();

    connection.query('SELECT * from asset', function(err, rows, fields) {
        if (err) throw err;

        console.log('The solution is: ', rows[0].solution);
    });

    connection.end();
};

How can I do the import? Thanks

2 Answers 2

2

You need to export the function from your module. Add:

exports.sqlTest = sqlTest;

to the bottom of your MYSQLConnector.js file.

Also, see the nodejs api documentation for more details.

Sign up to request clarification or add additional context in comments.

Comments

1

you're almost there, add "exports" in front of it:

exports.sqlTest = function (){
  var mysql      = require('mysql');
  var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'xxxx'
  });

  connection.connect();

  connection.query('SELECT * from asset', function(err, rows, fields) {
    if (err) throw err;

    console.log('The solution is: ', rows[0].solution);
  });

  connection.end();
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.