javascript - Some questions about using the mysql module to connect to the database
PHP中文网
PHP中文网 2017-05-16 13:37:28
0
1
391

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中文网

认证0级讲师

reply all(1)
小葫芦

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!