mssql + Typescript の実装サンプル

mssqlを使用したDB接続実装サンプル

〇サンプルに使用するテーブル

CREATE TABLE shopping_items (
    id bigint IDENTITY(1,1) NOT NULL,
    name varchar(40) COLLATE Japanese_CI_AS NOT NULL,
    price int NOT NULL,
    suryo int NULL,
    description varchar(100) COLLATE Japanese_CI_AS NULL,
    version int NOT NULL,
    CONSTRAINT shopping_items_pk PRIMARY KEY (id)
);

mssqlのインストール

node-mssql

npm install mssql
npm install @types/mssql

〇package.json

{
  "name": "aa",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/mssql": "^8.0.2",
    "mssql": "^8.1.2",
    "typescript": "^4.7.3"
  }
}

接続先の設定

import * as mssql from 'mssql';

// 接続先の設定
const config = {
    server: 'localhost',
    authentication: {
        type: 'default',
        options: {
            userName: 'aa00001',
            password: 'Xaa00001'
        }
    },
    trustServerCertificate: true,
    database: 'Test',
    // コネクションプールの設定
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    },
};

コネクションの確立

(async () => {
    try {
        // 接続の確立
        await mssql.connect(config);
    } catch (error) {
        console.log(error);
    }
})();

DB操作処理の記述

(async () => {
    try {
        // selectサンプル
        const result = await mssql.query(`select * from shopping_items`);
        console.log(result);
    } catch (error) {
        console.log(error);
    }
})();

トランザクション処理

(async () => {
    try {
        // トランザクションサンプル
        const tran = new mssql.Transaction();
        tran.begin(0, async (err) => {
            // INSERT バインド変数サンプル
            const result = await new mssql.Request(tran)
                .input('name', 'モンブラン')
                .input('price', 580)
                .input('suryo', 5)
                .input('description', '美味しい')
                .query("INSERT INTO shopping_items (name, price, suryo, description, version) VALUES(@name, @price, @suryo, @description, 1)")
                .catch(error =>{
                    console.log(error);
                });
            console.log(result);

            await tran.commit((err) => {
                if(err){
                    console.log(`commit error!`);
                }
                console.log('Commit');
            });
        });
        console.log(result);
    } catch (error) {
        console.log(error);
    }
})();

〇 index.tsの全体

import * as mssql from 'mssql';

// 接続先の設定
const config = {
    server: 'localhost',
    authentication: {
        type: 'default',
        options: {
            userName: 'aa00001',
            password: 'Xaa00001'
        }
    },
    trustServerCertificate: true,
    database: 'Test',
    // コネクションプールの設定
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    },
};

(async () => {
    try {
        // 接続の確立
        await mssql.connect(config)

        // selectサンプル
        const result = await mssql.query(`select * from shopping_items`);
        console.log(result);

        // トランザクションサンプル
        const tran = new mssql.Transaction();
        tran.begin(0, async (err) => {
            // INSERT バインド変数サンプル
            const result = await new mssql.Request(tran)
                .input('name', 'モンブラン')
                .input('price', 580)
                .input('suryo', 5)
                .input('description', '美味しい')
                .query("INSERT INTO shopping_items (name, price, suryo, description, version) VALUES(@name, @price, @suryo, @description, 1)")
                .catch(error =>{
                    console.log(error);
                });
            console.log(result);

            await tran.commit((err) => {
                if(err){
                    console.log(`commit error!`);
                }
                console.log('Commit');
            });
        });
    } catch (error) {
        console.log(error);
    }
})();