1.安裝組件promise-mysql: 命令 npm install promise-mysql --save
2. 創建一個文件專門放置連接mysql的代碼例如(MySql.js);
1 const mysql = require('promise-mysql'); 2 const Promise = require('bluebird'); 3 const pool = mysql.createPool({ 4 host : '101.201.198.218', 5 user : 'mesadm', 6 password : 'Jn6iPmvX45PKIvOM', 7 database : 'EXPSDATA' 8 }); 9 // 用using/dispsoer 模式構建連接 10 11 function getSqlConnection(){ 12 return pool.getConnection().disposer((c)=>{ 13 pool.releaseConnection(c); 14 }); 15 } 16 17 // 使用bluebird 封裝具有dispsoer功能的promise對象 18 function query(sql){ 19 return Promise.using(getSqlConnection(),(con)=>{ 20 return sql?con.query(sql):con; 21 }) 22 } 23 24 //向外暴露方法 25 module.exports ={ 26 pool, 27 getSqlConnection, 28 query 29 }
3.在使用連接mysql的vue文件中引入此文件
import MySQL from '../../../assets/server/MySQL.js'
let {query} = MySQL; let sql = `select * from '表名'where 條件`; query(sql).then((rows)=>{ let len = rows.length; if(len == 0) { that.$message.error('用戶名密碼不存在'); } else { that.$message.success('登錄成功');
console.log(rows)
} }).catch((e)=>{ console.log('error',e); });