NODEJS學習 sqlite操作
阿新 • • 發佈:2019-02-18
【程式碼段建立表】
var fs = require("fs");
var file = "test.db";var exists = fs.existsSync(file);
if(!exists) {
console.log("Creating DB file.");
fs.openSync(file, "w");
}
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);
db.each("SELECT rowid AS id, thing FROM Stuff where thing = '" + "Thing #1995800" + "'", function(err, row) {
console.log(row.id + ": " + row.thing);
});
return;
db.serialize(function() {
if(!exists) {
db.run("CREATE TABLE Stuff (thing TEXT)");
}
var stmt = db.prepare("INSERT INTO Stuff VALUES (?)");
//Insert random data
var rnd;
for (var i = 0; i < 10; i++) {
rnd = Math.floor(Math.random() * 10000000);
stmt.run("Thing #" + rnd);
}
stmt.finalize();
db.each("SELECT rowid AS id, thing FROM Stuff where id =11", function(err, row) {
console.log(row.id + ": " + row.thing);
});
});
db.close();
【程式碼段2:查詢表】
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);
db.each("SELECT * FROM result", function(err, row) {
console.log( "row:",row);
});
return;
【使用knex】
參考 http://knexjs.org 的例子, 提供一些更便於操作資料庫的包裝。