Export module for mysql connection

I played with Node.js and I wrote some test applications using node-mysql. I am trying to write a module that automatically establishes a connection to a database, so I do not need to write code to connect again and again. Here is what I wrote:

var mysql = require('mysql');

module.exports = function(mysql) {
  var client = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '12345'
  });
  return client;
}

But when I try to import this file into another * .js file, I get an error message:

~/work : $ node queryInfo.js
/Users/socomo22/work/queryInfo.js:3
client.connect();
       ^
TypeError: undefined is not a function
    at Object.<anonymous> (/Users/socomo22/work/queryInfo.js:3:8)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Since I'm new to Node.js, I'm not sure what I'm doing wrong. Please, help!

queryInfo.js // Code that requires the above module

var client = require('./connectMysql');

client.query("USE node");

client.query("INSERT INTO test(content) VALUES(?)", ['the content'],
  function(err, info) {
    if(err)
      return handle_error(err);
    console.log(info.insertId);
});


client.query('UPDATE test SET content = ?', ['new content'], function(err, info) {
  if(err)
    return handle_error(err);
  console.log(info.insertId);
});

client.end();
+4
source share
3 answers

node.js . , db. MySQL . u .

MySQL , . MySQL :

var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});

connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }

  console.log('connected as id ' + connection.threadId);
});

. node.

, :

var db = require("./connectMysql");
db.getConnection(function(err, connection) {
    // here u can run queries 
});

, MySQL createClient , - .

0

:

config.js

var mysql      = require('mysql');
var config;
config = {
    mysql_pool : mysql.createPool({
        host     : 'hede',
        user     : 'hede',
        password : 'hede',
        database : 'hede'
    })
};
module.exports = config;

js. :

var mysqlConf = require('config.js').mysql_pool;

    mysqlConf.getConnection(function (err, connection) {
        connection.query('{YOUR QUERY}' ,[{FIELDS}], function (err, rows) {
            connection.release();   //---> don't forget the connection release.
        });
    });
+2

according to https://github.com/felixge/node-mysql you need to call

client.connect();

after createConnection and before the first request.

0
source

Source: https://habr.com/ru/post/1624265/


All Articles