我是NodeJS和数据库的新手。我对程序的行为感到困惑。我只是试图创建表,然后将其删除。但是我的代码出了点问题。结果真的很奇怪。我运行了几次代码,结果却不同。结果示例:
First execution
[ { name: 'first' } ]
createTable error SQLITE_ERROR: table first already exists
[ { name: 'first' } ]
table first dropped
Second execution
[]
[]
table first(name text) created succesfully
Third execution
createTable error SQLITE_ERROR: table first already exists
[ { name: 'first' } ]
[ { name: 'first' } ]
table first dropped
下面列出的代码。如果有人可以指出我的错误,我将不胜感激。
import { Database } from 'sqlite3';
class DBWrapper {
private db: Database;
constructor(dbName: string) {
this.db = new Database(dbName, (error) => {
if (error) {
console.log('Database construction failed');
} else {
console.log('Database created successfully');
}
});
}
public createTable(tableName: string): void {
this.db.serialize(() => {
this.db.run('CREATE TABLE ' + tableName, (error) => {
if (error) {
console.log('createTable error ' + error.message);
} else {
console.log('table ' + tableName + ' created succesfully');
}
});
});
this.db.close();
this.db = new Database('sqlitest');
}
public printTables(): void {
this.db.serialize(() => {
this.db.all('select name from sqlite_master where type=\'table\'', (error, tables) => {
console.log(tables);
});
});
this.db.close();
this.db = new Database('sqlitest');
}
public clear(): void {
this.db.serialize(() => {
this.db.all('select name from sqlite_master where type=\'table\'', (error, tables) => {
if (error) {
console.log('error in select all tables');
} else {
tables.forEach((table) => {
this.db.run('DROP TABLE ' + table.name, (innerError) => {
if (innerError) {
console.log('drop table ' + table.name + ' error ' + innerError.message);
} else {
console.log('table ' + table.name + ' dropped');
}
});
});
}
});
});
this.db.close();
this.db = new Database('sqlitest');
}
}
const testDB = new DBWrapper('sqlitest');
testDB.createTable('first(name text)');
testDB.printTables();
testDB.clear();
testDB.printTables();
答案 0 :(得分:1)
在开始下一个命令之前,您需要等待每个命令完成。
通常,db.serialize()
会为您执行此操作,但是您将在每个命令之后创建一个新的db
实例,而该命令不知道前一个实例的挂起操作。
您应该重用db
实例。