LoginSignup
9
11

More than 3 years have passed since last update.

Node.js+Express経由でSQLite3にデータ登録する

Last updated at Posted at 2016-04-08

前回、Node.jsのインストールを実施しました。
CentOS7.2にNode.js環境を構築する

今回は、フレームワークであるExpressと、SQLite3を導入していきます。

Expressの導入

[am@Alnilam ~]$ npm install express

テスト用アプリを作る

test.js
let server = require('express')();
server.get('/', function(req, res){
  res.send('This is Anfield.');
});
server.listen(3000);

起動

node test.js

ブラウザでアクセスする
res.png

Expressのインストールは終わったので、SQLiteを導入します。
1台の貧弱なサーバにNode.js、DBなどすべて含む構成であるため
SQLiteを選択します。

インストール

[root@Alnilam ~]$ yum install sqlite
[am@Alnilam ~]$ npm install sqlite3
[am@Alnilam ~]$ sqlite3 -version
3.7.17 2013-05-20

インストールが終わったので、早速使ってみます。

ドライバのサンプルを動かす
参考ページ

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('sample');
db.serialize(function() {
  db.run('CREATE TABLE lorem (info TEXT)');
  var stmt = db.prepare('INSERT INTO lorem VALUES (?)');
  for (var i = 0; i < 10; i++) {
    stmt.run('Ipsum ' + i);
  }
  stmt.finalize();
  db.each('SELECT rowid AS id, info FROM lorem', function(err, row) {
    console.log(row.id + ': ' + row.info);
  });
});
db.close();

実行

[am@Alnilam ~]$ node testsqlite.js
1: Ipsum 0
2: Ipsum 1
3: Ipsum 2
4: Ipsum 3
5: Ipsum 4
6: Ipsum 5
7: Ipsum 6
8: Ipsum 7
9: Ipsum 8
10: Ipsum 9

SQLiteの確認

[am@Alnilam ~]$ sqlite3 sample
sqlite> .header on
sqlite> .mode column
sqlite> .table
sqlite> select * from lorem;
info      
----------
Ipsum 0   
Ipsum 1   
Ipsum 2   
Ipsum 3   
Ipsum 4   
Ipsum 5   
Ipsum 6   
Ipsum 7   
Ipsum 8   
Ipsum 9 

登録できました。次回こそ、簡単なAPIを作成したいと存じます。

9
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
11