我正在尝试在Express js中导入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_EMPTY_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,function(err,results){ console.log(结果); })。end();
它返回ER_ACCESS_DENIED_ERROR
答案 0 :(得分:2)
尝试使用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();