0

我正在尝试掌握Node(我主要使用python),所以我正在开发一个小项目来读取写入数据到sqlite数据库。

幸运的是,我在写入数据库时​​没有问题,但我似乎根本无法让查询工作。我已经在 sql 终端中测试了查询,它们是成功的。

到目前为止,我有类似的东西

const fs = require("fs");
const util = require("util");
const sqlite = require("sqlite");
const Promise = require("bluebird")


// const DATABASE = ":memory:";
const DATABASE = "./database.sqlite";

function insertDataIntoDatabase(transactions, db) {
    // Write each transaction into the database.
    let sqlStatement = "INSERT INTO Trx \
        (name, address, amount, category) \
        VALUES "
    for (var i = 0; i < transactions.length; ++i) {
        let trx = transactions[i];
        sqlStatement += util.format(
            "('%s', '%s', %d, '%s'), ",
            trx.name,
            trx.address,
            trx.amount,
            trx.category,
        );
    }
    sqlStatement = sqlStatement.substring(0, sqlStatement.length - 2);
    db.then(db => db.run(sqlStatement))
        .catch((err) => console.log(err));
}

function getTransactions (db, category) {
    // Return an array of valid transactions of a given category.
    let where = "";
    if (category) {
        where = util.format("WHERE category='%s'", category);
    }
    let sqlStatement = util.format("SELECT * from Trx %s", where);
    sqlStatement = "SELECT * from Trx";  // Trying to figure out whats happening
    console.log(sqlStatement);
    db.then(db => {
        db.all(sqlStatement)
        .then((err, rows) => {
            console.log(rows);  // undefined
            console.log(err);  // []
        })
    })
}

// Set up the db connection
const db = sqlite.open(DATABASE, { cached: true })
    .then(db => db.migrate({ force: 'last' }));


// Read transactions and write them to the database
fs.readFile("transactions.json", "utf8", (err, data) => {
    let transactions = JSON.parse(data).transactions;
    insertDataIntoDatabase(transactions, db);
})
// Get transaction data
getValidTransactions(db, 'credit');

// Close connection to DB
db.then(db => db.close());
4

1 回答 1

0

再看一遍,我认为问题在于 Node.js 的异步特性。查询成功,但当时我还没有将 json 文件中的数据插入数据库,因此查询为空。

于 2018-04-18T02:22:35.590 回答