我阅读了txt的每一行,并对其中的每一行执行了一些简单的数据库查询。
fillDatabase1做我想要的事情。它对每一行执行查询,当一切完成后,它等待数据库关闭,然后调用resolve。
fillDatabase2尽管与fillDatabase1非常相似,但似乎在执行每一行的查询之前运行了database.close,从而导致错误。
UnhandledPromiseRejectionWarning: Error: Cannot enqueue Query after invoking quit.
database.js
const mysql = require( 'mysql' )
const db_credentials = require('./config')
module.exports = class Database {
constructor() {
this.connection = mysql.createConnection( db_credentials );
}
query( sql, args ) {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err );
resolve( rows );
} );
} );
}
close() {
return new Promise( ( resolve, reject ) => {
this.connection.end( err => {
if ( err )
return reject( err );
resolve();
} );
} );
}
}
readFile.js
const fs = require('fs')
const readline = require('readline')
const stream = require('stream')
const mydatabase = require('../database/database.js')
updateDatabase()
const updateDatabase = async () => {
// 1) Fill Topics
await fillDatabase1()
console.log("fillDatabase1 completed")
// 2) Fill database2
await fillDatabase2()
console.log("fillDatabase2 completed")
}
const fillDatabase1= () => {
database = new mydatabase()
return new Promise((resolve, reject) => {
var instream = fs.createReadStream("C:\Users\prof_chaos\Desktop\mydata.txt")
var outstream = new stream()
var rl = readline.createInterface(instream, outstream)
var lineCount = 0
let outcome;
rl.on('line', async function(line) {
lineCount++;
let data = line.split('|')
let args = {mid: data[0], name: data[1], description: data[2], type: data[3]}
let sql = 'INSERT INTO topics SET ?'
outcome = await database.query(sql, args)
})
.on('close', () => {
console.log(`Succesfully added ${lineCount} lines to topics table`)
database.close().then(() => {
console.log('db connection closed - filled topics')
resolve()
})
})
})
}
const fillDatabase2 = () => {
return new Promise((resolve, reject) => {
database = new mydatabase()
var instream = fs.createReadStream("C:\Users\prof_chaos\Desktop\mydata2.txt")
var outstream = new stream()
var rl = readline.createInterface(instream, outstream)
var lineCount = 0
let topic;
let sql;
rl.on('line', async function(line) {
lineCount++;
let data = line.split('|')
sql = 'SELECT id FROM topics WHERE mid = ? LIMIT 1'
topic = await database.query(sql, [data[0]])
if(topic[0]) { // If SELECT found something
let args = {predicate: data[1], value: data[2], topic_id: topic[0].id}
sql = 'INSERT INTO topics_predicates_values SET ?'
let outcome = await database.query(sql, args)
} else {
console.log("mid " + data[0] + " not found in database")
}
})
.on('close', () => {
database.close().then(() => {
console.log(`Succesfully added ${lineCount} lines to topics_predicates_value table`)
resolve()
})
})
})
}