這個教程不管node,express,koa都可以用下面方法連接,這裏用koa做個參考
新建文件目錄,我是這樣子的
很多教程都沒有涉及到版本,所以讓很多初學者,拷貝他的代碼,出現錯誤問題
我的版本:
"dependencies": {
"koa": "^2.6.2",
"mysql": "^2.16.0"
}
1.設置配置文件
// default.js
// 設置配置文件
const config = {
// 啓動端口
port: 3000,
// 數據庫配置
database: {
DATABASE: 'ceshi',
USERNAME: 'root',
PASSWORD: '1234',
PORT: '3306',
HOST: 'localhost'
}
}
module.exports = config
2.連接數據庫
// mysql/index.js
var mysql = require('mysql');
var config = require('../config/default.js')
var pool = mysql.createPool({
host : config.database.HOST,
user : config.database.USERNAME,
password : config.database.PASSWORD,
database : config.database.DATABASE
});
class Mysql {
constructor () {
}
query () {
return new Promise((resolve, reject) => {
pool.query('SELECT * from ceshidata', function (error, results, fields) {
if (error) {
throw error
};
resolve(results)
// console.log('The solution is: ', results[0].solution);
});
})
}
}
module.exports = new Mysql()
3.設置服務器
// index.js
const Koa = require('koa')
const config = require('./config/default')
const mysql = require('./mysql')
const app = new Koa()
app.use(async (ctx) => {
let data = await mysql.query()
ctx.body = {
"code": 1,
"data": data,
"mesg": 'ok'
}
})
app.listen(config.port)
console.log(`listening on port ${config.port}`)
4.啓動服務器,去瀏覽器訪問
先去數據庫添加點數據
node index.js
打開瀏覽器localhost:3000, 然後你就會看到以下數據,自己添加的數據查詢出來了
然後其他相關操作,可以看mysql相關API,我下次也會分享出來
首發於微信公衆號:node前端
不妨關注一下,我們一起學習
回覆:100
有福利哦