<分区>
我需要在我的 express 应用程序中使用 Mysql。我该如何实现?
<分区>
我需要在我的 express 应用程序中使用 Mysql。我该如何实现?
最佳答案
你应该用这样的连接池来实现它:
const mysql = require('mysql');
const pool = mysql.createPool({
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
const getConnection = () => {
return new Promise((resolve, reject) => {
pool.getConnection(function(err, connection) {
if (err) {
reject(err);
}
else {
resolve(connection);
}
});
});
}
module.exports = {
getConnection,
};
你可以像这样从这个池中获取连接:
getConnection().then((conn) => {
conn.query(<your query>, (error, results, fields) => {
// do things here;
conn.release();
});
})
关于mysql - 在 Express.js 应用程序中处理 Mysql 数据库的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50581357/