nodejs之数据库连接

nodejs 对 MySQL、mongodb、redis 数据库的连接方式。

MySQL:

var mysql = require('mysql')
var { MYSQL } = require('../config/default.js')

// 创建连接池
var pool = mysql.createPool({
  host: MYSQL.HOST,
  port: MYSQL.PORT,
  user: MYSQL.USERNAME,
  password: MYSQL.PASSWORD,
  database: MYSQL.DATABASE
})

// 查询函数
const query = (sql, params) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        resolve(err)
      } else {
        connection.query(sql, params, (error, results, fields) => {
          if (error) {
            reject(error)
          } else {
            resolve(results)
          }

          connection.release(err => {
            if (err) {
              console.log('DB-关闭数据库连接异常')
            }
          })
        })
      }
    })
  })
}

module.exports = query

用法示例:

const query = require('../mysql')

// 查询所有用户
const getallusers = () => {
  const _sql = 'SELECT * FROM tb_user'

  return query(_sql)
}

// 查询单个用户信息
const getuser = (username) => {
  const _sql = 'SELECT * FROM tb_user WHERE username = ?'

  return query(_sql, [username])
}

module.exports = {
   getallusers,
   getuser
}
 

 

mongodb:

const MongoClient = require('mongodb').MongoClient
const { MONGO } = require('../config/default')

// 无账号登录
let url = 'mongodb://' + MONGO.HOST + ':' + MONGO.PORT + '/'

// 有账号登录,对于有特殊字符的密码需要 encodeURIComponent
if (MONGO.USERNAME && MONGO.PASSWORD) {
  url = 'mongodb://' + MONGO.USERNAME + ':' +
    encodeURIComponent(MONGO.PASSWORD) + '@' + MONGO.HOST + ':' + MONGO.PORT + '/'
}

class Mongo {
  static getInstance() {
    if (!Mongo.instance) {
      Mongo.instance = new Mongo
    }
    return Mongo.instance
  }

  constructor() {
    this.client = ''
    this.connect()
  }

  connect() {
    return new Promise((resolve, reject) => {
      if (!this.client) {
        new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true }).connect((err, client) => {
          if (err) {
            reject(err)
          } else {
            this.client = client.db(MONGO.DATABASE)
            resolve(this.client)
          }
        })
      } else {
        resolve(this.client)
      }
    })
  }
}

// 暴露实例,全局通用
module.exports = Mongo.getInstance()

用法示例:

const mdb = require('../../mdb')

module.exports = {
  // 更新文章
  updateArticleInfo (id, data) {
    return new Promise((resolve, reject) => {
      mdb.connect().then(async db => {
        let articleColl = db.collection('article')

        articleColl.updateOne({ _id: ObjectId(id) }, {
          $set: data
        }, async (err, res) => {
          if (!err) {
            let [_data] = await articleColl.find({ _id: ObjectId(id) }).toArray()
            resolve(_data)
            return
          }
          reject(err)
        })
      })
    })
  }
}

 

redis:

// https://www.npmjs.com/package/ioredis
const Redis = require('ioredis')
const { REDIS } = require('../config/default')

// redis 直接暴露 ioredis 的实例即可
module.exports = new Redis({
  port: REDIS.PORT,         // Redis port
  host: REDIS.HOST,         // Redis host
  prefix: REDIS.PREFIX,     //存诸前缀
  // ttl: REDIS.TTL,        //过期时间   
  // family: REDIS.FAMILY,
  password: REDIS.PASSWORD
  // db: 0
})

用法示例:

const Redis = require('../redis')

const redisFun = {
  set(key, value) {
    return new Promise((resolve, reject) => {
      Redis.set(key, value).then(res => {
        resolve()
      }).catch(err => {
        reject()
      })
    })
  },
  get(key) {
    return new Promise((resolve, reject) => {
      Redis.get(key).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

module.exports = redisFun

 

posted @ 2020-07-15 10:45  前端杂货  阅读(1690)  评论(0编辑  收藏  举报