刹那(せつな)の瞬き

Willkömmen! Ich heiße Setsuna. Haben Sie etwas Zeit für mich?

UbuntuでNode.jsからSQLServer2019に接続する

SQL Server on Linux の評価の続きです。

Ubuntu で直近の Node.js 環境を整えたばかりなので、Node.js から SQL Server on Linux に接続してみます。

1. 環境

なお、参照しているデータベースは「Ubuntu18.04のSQLServer2019にデータベースファイルを移行する」を前提にしています。

2. 接続とクエリ実行

公式サイトを参考に試してみました。

SQLServer に接続後、クエリを実行して結果を表示するサンプルです。

(1) プロジェクトの準備

今回はホーム直下に hellomssql を作成します。

$ cd ~
$ mkdir hellomssql
$ cd hellomssql
$ npm init -y
$ npm install tedious
$ touch index.js
$ code .

VS Code が起動するので、index.js を編集します。

var Connection = require('tedious').Connection;
var config = {
    server: 'localhost',
    authentication: {
        type: 'default',
        options: {
            userName: 'sa',
            password: 'abcd1234$'
        }
    },
    options: {
        database: 'NorthwindJ'
    }
};
var connection = new Connection(config);
connection.on('connect', function(err) {
    console.log("Connected");
    executeStatement();
});
var Request = require('tedious').Request;
function executeStatement() {
    request = new Request("SELECT 氏名, フリガナ, CONVERT(nvarchar, 誕生日, 111) as birthday FROM 社員;", function(err, rowCount) {
        if (err) {
            console.log(err);
        } else {
            console.log(rowCount + ' rows returned');
        }
    });
    var result = "";
    request.on('row', function(columns) {
        columns.forEach(function(column) {
            if (column.value === null) {
                console.log('NULL');
            } else {
                result += column.value + " ";
            }
        });
        console.log(result);
        result = "";
    });
    connection.execSql(request);
}

公式サイトのままだと、rowCount が表示されないので、少しコードを書き換えました。

(2) 実行

nodeから index.js を起動します。

$ node index.js 
Connected
森上 偉久馬 モリウエ イクマ 1967/10/25 
葛城 孝史 カツラギ コウシ 1961/02/03 
加藤 泰江 カトウ ヤスエ 1968/02/02 
川村 匡 カワムラ タダシ 1957/12/08 
松沢 誠一 マツザワ セイイチ 1965/03/30 
成宮 真紀 ナルミヤ マキ 1968/03/03 
山本 雅治 ヤモト マサハル 1967/01/16 
青木 俊之 アオキ トシユキ 1966/08/21 
小川 さよ子 オガワ サヨコ 1966/09/23 
9 rows returned

とりあえず意図したようには動いてるようです。

ここから業務で使えるように、JSON を返して、React で表示して、Electron で...と、まだまだゴールは遠いですが、取っ掛かりとしては十分です。

3. 参考にしたサイト