使用expressjs导入sql文件

nvbavucw  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(416)

我正在尝试导入expressjs中的sql文件。我尝试了下面的代码,但是在使用mssql和fs模块时它不起作用

fs.readFile(__dirname +'/database.sql', function (err, sqlFile) {
        if(err) { throw err; }
        connection.query(sqlFile, function(err, results) {
            if (err) throw err;
            console.log(results); 
          }); 
        console.log(sqlFile);
});

它不起作用,它说er\u empty\u query:查询是空的
当我尝试execsql模块时。

var execsql = require('execsql'),
dbConfig = {
    host: 'localhost',
    user: 'root',
    password: 'root'
},
sql = 'use db_cam;',
sqlFile = __dirname + '/db.sql';

execsql.config(dbconfig).exec(sql).execfile(sqlfile,函数(err,results){console.log(results);})。结束();
它返回er\ U access\ U denied\错误

qyyhg6bp

qyyhg6bp1#

使用es6尝试以下代码:

import mysql from 'mysql';
    import * as path from 'path';
    import fs from 'fs';

    class DBManager {
      constructor() {
        this.conn = mysql.createConnection({
          host: process.env.DB_HOST,
          user: process.env.DB_USER,
          password: process.env.DB_PASSWORD,
          port: process.env.DB_PORT
        });
        let connection=this.conn;
        this.setCurrentDB(function (data) {
          if (data == 'refused') {
            let queries = fs.readFileSync(path.join(__dirname, 'db_file.sql'), { encoding: "UTF-8" }).split(";\n");
            for (let query of queries) {
              query = query.trim();
              if (query.length !== 0 && !query.match(/\/\*/)) {
                connection.query(query, function (err, sets, fields) {
                  if (err) {
                    console.log(`Importing failed for Mysql Database  - Query:${query}`);
                  } else {
                    console.log(`Importing Mysql Database  - Query:${query}`);
                  }
                });
              }
            }
          } else if (data == 'connected') {
            console.log(`Connected to Mysql Database  `);
          }
        });
        this.conn.connect(function (err) {
          if (err) {
            console.log(`Mysql Database connection error`);
          } else {
            console.log(`Connected to Mysql Database`);
          }
        });
      }

  setCurrentDB(callback) {
    this.conn.query(`USE dbname`, function (err, rows) {
      if (err) {
        if (err.errno == 1049) {
          console.log(`${err.sqlMessage} : Failed to connect MySql database`);
          return callback('refused');
        } else {
          console.log(`Mysql Database connection error`);
          return callback('refused');
        }
      } else {
        return callback('connected');
      }
    });
  }

    }
    export default new DBManager();

相关问题