1.首先安装mysql
npm install -S mysql
2.项目中新建db文件夹,并在下面创建config.js用来存储mysql需要的相关配置
module.exports = {
host: 'localhost',
user: 'root',
password: 'password',
database: 'database'
}
3.db文件夹下创建index.js
const mysql = require('mysql')
const {
host,
user,
password,
database
} = require('./config')
function connect() {
return mysql.createConnection({
host,
user,
password,
database
})
}
function querySql(sql) {
const conn = connect()
return new Promise((resolve, reject) => {
try {
conn.query(sql, (err, results) => {
if (err) {
console.log(`查询失败,原因:${JSON.stringify(err)}`)
reject(err)
} else {
console.log(`查询成功,${JSON.stringify(results)}`)
resolve(results)
}
})
} catch (e) {
reject(e)
} finally {
conn.end()
}
})
}
module.exports = {
querySql
}