gpt4 book ai didi

javascript - Javascript - 如何结束与数据库的连接?

转载 作者:行者123 更新时间:2023-12-03 00:57:52 25 4
gpt4 key购买 nike

我有一个代码,它运行良好(从数据库获取数据),但是当我从终端运行它时(例如node db.js) - 它返回数据但永远不会关闭(无法在终端中输入下一个命令。

var mysql = require('mysql');

var connection = mysql.createConnection({
host: '...',
user: '...',
password: "...,
port : ..., //port mysql
database: '...'
});

connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM table", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

.js 末尾应该添加什么?

最佳答案

您可以使用connection.end();结束连接您必须将其添加在查询之后,因为必须先完成查询。这是您修改后的代码:

var mysql = require('mysql');

var connection = mysql.createConnection({
host: '...',
user: '...',
password: "...,
port : ..., //port mysql
database: '...'
});

connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM table", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
connection.end();
});

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

https://github.com/mysqljs/mysql#introduction

关于javascript - Javascript - 如何结束与数据库的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52745876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com