Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@PhilOwen
Last active September 3, 2020 17:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhilOwen/7917dcb9791edd5e2916 to your computer and use it in GitHub Desktop.
Save PhilOwen/7917dcb9791edd5e2916 to your computer and use it in GitHub Desktop.
Node.jsでSQLiteを読み書き

SQLiteのデータベースを、Node.jsから使ってみる。
npm run writeと実行すると、カレントのディレクトリに 数件のレコードが入ったrestaurant.sqliteができる。
npm run readと実行すると、それを読み出す。
超簡単だが、ちょっとした実験アプリで使うにはわりと便利そう。

実行前には、npm installすること。

Express.jsでSQLiteを使うときも、原理はこれ。
Express.jsの公式サイトに ドキュメントがあって、かなりすっきりまとまっている(が、英語)。

{
"name": "sqlite-sample",
"version": "1.0.0",
"description": "",
"scripts": {
"write": "node write.js",
"read": "node read.js"
},
"author": "Phil Owen",
"license": "MIT",
"dependencies": {
"sequelize": "^3.27.0",
"sqlite3": "^3.1.8"
}
}
const sqlite3 = require('sqlite3');
let db = new sqlite3.Database('restaurant.sqlite');
db.serialize(() => {
db.each('SELECT rowid AS id, info, score FROM restaurant',
(err, row) =>
console.log(row.id + ': ' + row.info + '(' + row.score + ' pt)')
);
});
db.close();
const sqlite3 = require('sqlite3');
let db = new sqlite3.Database('restaurant.sqlite');
db.serialize(() => {
db.run('CREATE TABLE restaurant (info TEXT, score INT)');
let stmt = db.prepare('INSERT INTO restaurant VALUES (?, ?)');
stmt.run('Costa Coffee', 3);
stmt.run('The Snug', 4)
stmt.run('The Wrestlers Pub', 5);
stmt.finalize();
});
db.close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment