繁体   English   中英

如何在配置文件中连接mysql?

[英]How to connect with mysql in config file?

我想要做的是在我的项目中的配置文件中连接 MySQL 数据库。

配置/db.js

const mysql = require('mysql')

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'mydatabase'
})

const connectDb = async () => {
  const conn = await connection.connect(function (err) {
    if (err) {
      return console.error("error: ", err.message);
    }

    console.log("Connected to MySql server");
  });
};

服务器.js

const connectDB = require("./config/db");

connectDB();

我已经这样做了,在我的终端中显示了这个错误:TypeError: connectDb is not a function

如何在配置文件中连接 MySQL?

您需要导出连接动词,并删除整个“connectDb”函数

配置/db.js

const mysql = require('mysql')

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'mydatabase'
})

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

服务器.js

const database = require("./config/db");
database.queryOrAnythignElse();

您可能想再次学习 js 的基础知识以及什么是 module.exports 等...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM