什么是在Express.js应用程序中处理Mysql数据库的最佳方法?

时间:2018-05-29 09:52:46

标签: mysql node.js express

我需要在我的快递应用程序中使用Mysql。我该如何实施呢?

2 个答案:

答案 0 :(得分:3)

您应该使用如下连接池实现它:

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();
   });
})

答案 1 :(得分:0)

尝试检查此链接https://medium.com/@avanthikameenakshi/building-restful-api-with-nodejs-and-mysql-in-10-min-ff740043d4be

使用npm npm install mysql --save

安装mysql

在您的app.js或根目录中的index.js连接到mysql:

var mysql = require("mysql");
//Database connection
app.use(function(req, res, next){
    res.locals.connection = mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : ' ',
        database : 'test'
    });
    res.locals.connect();
    next();
});

现在在res中添加了mysql连接,您现在可以通过调用自定义端点中的res.locals.connection.query来进行查询