在 node.js 工程下,安装 MySQL 模块
// MySQL
npm install mysql
// 使用 淘宝镜像 安装MySQL
npm install mysql --registry=https://registry.npm.taobao.org
在需要使用的地方
// 导入 MySQL
const mysql = require('mysql')
// 创建连接
const pool = mysql.createPool({
host : 'localhost',
user : 'your MySQL username',
password : 'your MySQL password',
database : 'form Name'
})
发起连接
// 连接数据库
pool.getConnection((err, connection) => {
if (err) {
console.log('connection MySQL fail')
return
}
console.log('MySQL connection supooleed id : ' + connection.threadId)
// 释放连接
connection.release()
})
查询测试 , 确保你的数据库里有一些数据
pool.query(`SELECT * FROM your mysql form name`, (err, res, fie)=>{
if (err) {
console.log(err)
return
}
console.log(res)
})