search

Home  >  Q&A  >  body text

javascript - Some questions about using the mysql module to connect to the database

Look at the example code like this;

const mysql = require('mysql');

exports.base = (sql, data, callback) => {
    // 创建数据库连接
    let connection = mysql.createConnection({
        host: 'localhost', //数据库所在的服务器域名或者IP
        user: 'root', //用户名
        password: '', //密码
        database: 'book' //数据库名称
    });
    // 执行连接动作
    connection.connect();
    // 执行数据库操作
    connection.query(sql, data, (err, rows) => {
        if (err) throw err;
        callback(rows);
    });
    // 关闭数据库
    connection.end();
}

It should look like this

const mysql = require('mysql');

exports.base = (sql, data, callback) => {
    // 创建数据库连接
    let connection = mysql.createConnection({
        host: 'localhost', //数据库所在的服务器域名或者IP
        user: 'root', //用户名
        password: '', //密码
        database: 'book' //数据库名称
    });
    // 执行连接动作
    connection.connect();
    // 执行数据库操作
    connection.query(sql, data, (err, rows) => {
        if (err) throw err;
        callback(rows);
        // 关闭数据库
        connection.end();
    });
    
}

I just feel that closing the database connection should be done in the callback of the query. If it is written like the first way and the query is not finished, is it inappropriate to close the database? The internal principle of this mysql module is not very clear;
Hope everyone can clear up the confusion;

PHP中文网PHP中文网2747 days ago418

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-16 13:39:28

    Documentation:

    Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

    So, calling end()不会马上关闭连接,要等剩余的查询执行完才关闭,该触发的回调还是触发。destroy() will directly close the connection.

    The specific implementation is to put all operations into the queue for execution. end()Just put a Quit operation into the queue, and it is actually closed after the Quit operation is executed.

    reply
    0
  • Cancelreply