Mysql module is a third-party module hosted on npm. It provides the ability to link and operate MySQL databases in the Node.js project.
To use it in a project, you need to run the following command on the console to install MySQL as a project dependency package:
npm i mysql
Configure the MySQL module
Before using the MySQL module to operate the database, you must first configure the MySQL module. The main configuration steps are as follows:
// 1.导入mysql模块
const mysql=require('mysql')
// 2.建立与mysql数据库的连接关系
const db=mysql.createPool({
host:'127.0.0.1', // 数据库的ip地址
user:'root', // 登陆数据库的账号
password:'', // 登陆数据库的密码
database:'mysql', // 指定要操作的数据库
})
// 测试mysql模块能否正常工作
// 调用db.query()函数,指定要执行的SQL语句,通过回调函数拿到执行结果
db.query('select 1',(err,result)=>{
// mysql模块工作期间报错了
if(err) return console.log(err.message)
// 能够成功的执行sql语句
console.log(result) // 控制台输出[ RowDataPacket { '1': 1 } ],表明测试成功
})