express 连接mysql数据库 操作数据库
dearweb
发布:2021-08-26 14:36:25阅读:
进入express学习之后,不少小伙伴就急于想掌握数据库的链接和操作方式,今天小编满足一下大家的好奇心,将express里面连接操作数据库的方法讲一下。
新建连接数据库文件
首先我们在express下新建一个文件夹db并在里面新建一个dbConfig.js用来链接操作数据库

连接操作数据库方法
然后接下来我们在dbConfig.js连接和操作mysql数据库
引入 mysql方法
const mysql = require('mysql')
// 连接数据库
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'xinglong0921',
database: 'dearweb',
port: 3306,
})
// 连接
connection.connect()
const sql = 'select * from dw_ecms_article' // 执行查询语句
connection.query(sql, (err, result) => {
if (err) {
console.log(err)
return
}
console.log(result) // 打印查询到的数据
connection.destroy() // 释放资源
})上文所讲到的就是利用express框架链接操作mysql数据库的方法,你看懂了吗?
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧