我是 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();