Pergunta

I'm learning nodejs and using 'mysql' module. With this function I want to verify if a name already exists in the database.

I have the current error

TypeError: Object #<Handshake> has no method 'query'

I think it is related to "this.query" but can't find a way to fix it.

Code

var mysql = require('mysql');
var conexao_bd = mysql.createConnection({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'db_name'
});

function verifica_nome(n){
    var bool = false;
    conexao_bd.connect(function(err){
        if(err){
            return console.log("Aconteceu um erro quando se tentava ligar à base de dados. Erro: "+err);
        }
        else{
            this.query("SELECT name FROM Users WHERE name=?", [n], function(err,rows){
                if(err != null){ this.end("Erro na query: "+err); }
                else{
                    if(rows[0]!=n){ bool=true; this.end(function(err){ return bool;})}
                    else{ this.end(function(err){ return bool;})}
                }
            });
        }
    });
}
Foi útil?

Solução

You should use conexao_bd, which is the connection object, and not this:

conexao_bd.query(...);
conexao_bd.end();

Outras dicas

You want to do what robertklep said when query'n, but don't call end (), you will close the connection. With your simple example, I'm going to assume you create the db connection when your app/module starts/required, so only close your connection when your app ends. I believe you'll simply need to set up an even on process.on('exit'), like so:

process.on('exit', function() {
    conexao_bd.end();
});

That way, your connection closes only when your app ends, and not after your first query.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top