构建mysql + nodejs + express应用的最佳方法

编程入门 行业动态 更新时间:2024-10-27 06:20:57

构建mysql + nodejs + express应用的最佳<a href=https://www.elefans.com/category/jswz/34/1771314.html style=方法"/>

构建mysql + nodejs + express应用的最佳方法

我使用mysql(没有序列号),通常在module.export函数中创建连接,然后从其他文件中要求它,例如:

var db;
module.exports={
getConnection = function (){return new Promise(function(resolve, reject){
// db = mysql connection stuff
resolve(db)
});}, 
//other database related operations similarly
}

现在,我想将所有内容分开,例如,我想要一个userModel,它将具有一些与用户相关的数据库操作,这些操作将仅导入db连接,依此类推;但是实现这一目标的最佳方法是什么?谢谢。

回答如下:

由于它的使用范围很广,并且不存在变量命名冲突的高风险,所以我更喜欢将其添加到全局对象中。然后,您不必确保已将其包含,传递或从模块中导入。

请考虑以下示例:

// in your application initialization file such as app.js

// require items …
const mysql = require('mysql');

const connection = mysql.createPool({
  connectionLimit: 10,
  host: process.env.DB_HOST || '127.0.0.1',
  user: process.env.DB_USER || 'local_user',
  password: process.env.DB_PASSWORD || 'local_password',
  database: process.env.DB_NAME || 'local_database',
  multipleStatements: true, 
  charset: 'utf8mb4' // necessary if you might need support for emoji characters
});

connection.on('connection', function (connection) {
  // handy for testing
  console.log('Pool id %d connected', connection.threadId);
});

connection.on('enqueue', function () {
  // handy for testing
  console.log('Waiting for available connection slot');
});

// make the connection global via the the variable db
global.db = connection;


// everywhere else in your app, use the now global db variable when running queries

  db.query(
    'INSERT INTO users SET ?', [{name: "John Smith"}], function(error, results, fields) {
      if (error) throw error;
      console.log(results);
    });
  }

更多推荐

构建mysql + nodejs + express应用的最佳方法

本文发布于:2024-05-07 03:25:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   mysql   express   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!