5
votes

I tried to use mySQL connection to do INSERT. But it says connection.query() is not a function. I can do INSERT in the sql.js file, but cannot in controller.js.

controller.js (where I want to do INSERT)

var connection=require('../../sql');
exports.render=function(req,res){
  res.render('login',{

  });
};
exports.create=function(req,res){
  res.render('signin');
};
exports.signin=function(req,res){
  var data  = {usr: 'goi', pwd: 'me'};
  connection.query('INSERT INTO login SET ?', data, function(err, result) {
    
  });
    res.render('layout');
};

sql.js (where I connected to MySQL)

var mysql=require('mysql');
var connection=mysql.createConnection({
  host:'127.0.0.1',
  port: '3306',
  user:'root',
  password:'12345',
  database:'db'
});

connection.connect(function(error){
  if(!!error){
    console.log(error);
  }else{
    console.log('Connected!:)');
  }
});

module.exorts=connection;
1
Simple typo in sql.js; module.exorts=connection; should be module.exports=connection;.RyanZim

1 Answers

0
votes

I had this error within an 'async function'. In my case my call to the pool was not preceded by the the await keyword.

ERROR:

let conn = pool.getConnection();

NO ERROR:

let conn = await pool.getConnection();