const dbPath = path.join(__dirname, 'test.db') const db = new sqlite.Database(dbPath)
const sqls = [`CREATE TABLE test( id CHAR(64) NOT NULL PRIMARY KEY CHECK(LENGTH(id) == 64), timeStamp INTEGER NOT NULL, state INTEGER NOT NULL DEFAULT 0)` , 'CREATE INDEX index_id ON txs(id)' , 'CREATE INDEX index_timeStamp ON txs(timeStamp)' , 'CREATE INDEX index_state ON txs(state)' ]
db.serialize(() => { for (let sql of sqls) { db.run(sql, (err) => { if (err) { console.error(err) } else { console.log('SQL executed.') } }) } })
db.serialize(() => { const stmt = db.prepare("INSERT INTO test VALUES (?, ?, ?)") for (const item of items) { stmt.run(item.hash, item.ts, item.state, (err) => { if (err) { console.error(err) } else { console.log('INSERT', item.hash) } }) } stmt.finalize() })
3. 查询
1 2 3 4 5 6 7 8 9 10 11
db.serialize(() => { db.each("SELECT * FROM test WHERE state=0", (err, row) => { if (err) { console.error('SELECT state=0 error:', err) } else { // do something here } }, (err, count) => { // do something here }) })
4. 更新
1 2 3 4 5 6 7
db.run("UPDATE test SET state=1 WHERE state=0", (err) => { if (err) { console.error('UPDATE txs error:', err) } else { console.log('UPDATE state to 1') } })