数据库连接操作

安装mysql 数据库

npm install mysql --save

配置连接 单一连接

const mysql = require('mysql');
const conn = mysql.creatConnection({
       host:'localhost',
       user:'数据库用户名',
       password:'数据库的密码',
       database:'数据库的名字'
})

执行查询操作

conn.query(sql, (err, result)=>{
     if (err) throw err;
     //处理结果集 增删改查
     //......
})

单一连接模块封装

const mysql = require('mysql');
// 配置连接 连接池
const pool = mysql.createConnection({
     host:'localhost',
     user:'数据库用户名',
     password:'数据库密码',
     database:'数据库名字',
})
// 实现连接
module.exports = function(sql) {
    return new Promise((resolve, reject) => {
    //从连接池中获取连接
       conn.query(sql, (err, result) => {
       if (err) reject(err);
       resolve(result);
       })
    })
}

配置连接池

const mysql = require('mysql');
// 配置连接 连接池
const pool = mysql.createPool({
    host:'localhost',
    user:'数据库用户名',
    password:'数据库密码',
    database:'数据库名字',
    connectionLimit:10
})

建立连接

//方式一
pool.query(sql, (error, results)=> {
    if (error) throw error;
    //处理结果
});
//方式二
pool.getConnection((err, connection) => {
    if (err) throw err;
    connection.query(sql, (err, results, fields) => {
        connection.release();
        if (error) throw error;
    })
})

连接池模块封装

const mysql = require('mysql');
const pool = mysql.createPool({
      host:'localhost',
      user:'数据库用户名',
      password:'数据库密码',
      database:'数据库名字',
      connectionLimit: 10
})
//实现连接
module.exports = function(sql){
    return new Promise((resolve, reject) => {
        pool.getConnection((err, results) => {
            if (err) reject(err);
            connection.query(sql, (err, result) => {
                connection.release();
                if (err) reject(err);
                resolve(result);
            })
        })
    })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值