node连接数据库

一、在package.json依赖模块添加: "mysql" : "latest",执行npm install;

二、module目录下新建mysql.js:

 1      const mysql = require('mysql');
 2    //连接配置
 3    module.exports = function(){
 4           let config = mysql.createConnection({//写json
 5                        host = "localhost", //数据库地址
 6                        user = "root", //数据库用户名
 7                        password = "root", //数据库密码
 8                        port = "3306", //端口号
 9                        database = "node" //数据库名
10          });
11          //开始连接
12          config.connect();
13          //进行数据库操作  1.数据库代码 2.回调(错误信息,返回的数据)
14          config.query('select * from `user`',(err,data) => {
15                console.log(data);
16          });
17         //结束连接
18         config.end();        
19      }

原文地址:https://www.cnblogs.com/licurry/p/6723233.html