0

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

1 回答 1

1

在开始下一个命令之前,您需要等待每个命令完成。

通常,db.serialize()会为您执行此操作,但您db在每个命令之后创建一个新实例,它不知道前一个实例的挂起操作。

您应该重用该db实例。

于 2018-11-07T01:43:41.470 回答