建立mysql连接最基本的步骤

//1. 引入mysql模块
const mysql = require('mysql');

//2. 设置数据库配置,四个基本参数要有
const db = {
    host: 'localhost',
    user: 'root',
    password: 'pwd',
    database: 'mydb'
};

//3. 实例化连接,利用createConnection()方法
const connection = mysql.createConnection(db);

//4. 建立连接
connection.connect();

//5. 利用Promise创建api,增删改查
const readSql = "SELECT * FROM mydb.table;"

const read = () => {
    return new Promise(resolve => {
        connection.query(readSql, (err, result) => {
            if (err) throw err;
            resolve(result);
        });
    });
}

//6. 导出api
module.exports = { read };  //read是个方法,必须加大括号。

 

posted @ 2021-10-16 09:53  巨魔战将  阅读(782)  评论(0编辑  收藏  举报