クイック スタート:Node.js を使用して Azure Database for PostgreSQL - Single Server に接続し、データにクエリを実行する

適用対象: Azure Database for PostgreSQL - 単一サーバー

重要

Azure Database for PostgreSQL - シングル サーバーは廃止パスにあります。 Azure Database for PostgreSQL - フレキシブル サーバーにアップグレードすることを強くお勧めします。 Azure Database for PostgreSQL - フレキシブル サーバーへの移行の詳細については、Azure Database for PostgreSQL 単一サーバーの現状に関するページをご覧ください。

このクイックスタートでは、Node.js アプリケーションを使用して、Azure Database for PostgreSQL に接続します。 ここでは、SQL ステートメントを使用してデータベース内のデータを照会、挿入、更新、削除する方法を説明します。 この記事の手順では、Node.js を使用した開発には慣れているものの、Azure Database for PostgreSQL の使用は初めてであるユーザーを想定しています。

前提条件

pg クライアントのインストール

pg をインストールします。pg は、Node.js 用の PostgreSQL クライアントです。

インストールするには、コマンド ラインから JavaScript の npm (node package manager) を実行して、pg クライアントをインストールします。

npm install pg

インストールされたパッケージを一覧表示して確認します。

npm list

接続情報の取得

Azure Database for PostgreSQL に接続するために必要な接続情報を取得します。 完全修飾サーバー名とログイン資格情報が必要です。

  1. Azure portal で、作成したサーバー (たとえば、mydemoserver) を検索して選択します。

  2. サーバーの [概要] パネルから、サーバー名管理者ユーザー名を書き留めます。 パスワードを忘れた場合も、このパネルからパスワードをリセットすることができます。

    Azure Database for PostgreSQL の接続文字列

Node.js での JavaScript コードの実行

Node.js は、Bash シェル、ターミナル、または Windows コマンド プロンプトから「node」と入力して起動できます。起動後、サンプルの JavaScript コードをコピーし、プロンプトに貼り付けて対話形式で実行してください。 または、JavaScript コードをテキスト ファイルに保存し、パラメーターとしてそのファイル名を使用して node filename.js を起動して実行することもできます。

接続、テーブルの作成、データの挿入

接続し、CREATE TABLE および INSERT INTO SQL ステートメントを使用してデータを読み込むには、次のコードを使用します。 PostgreSQL サーバーとのインターフェイスには、pg.Client オブジェクトを使用します。 サーバーへの接続を確立するには、pg.Client.connect() 関数を使用します。 PostgreSQL データベースに対して SQL クエリを実行するには、pg.Client.query() 関数を使用します。

host、dbname、user、password の各パラメーターは、サーバーとデータベースの作成時に指定した値に置き換えてください。

const pg = require('pg');

const config = {
    host: '<your-db-server-name>.postgres.database.azure.com',
    // Do not hard code your username and password.
    // Consider using Node environment variables.
    user: '<your-db-username>',     
    password: '<your-password>',
    database: '<name-of-database>',
    port: 5432,
    ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
    if (err) throw err;
    else {
        queryDatabase();
    }
});

function queryDatabase() {
    const query = `
        DROP TABLE IF EXISTS inventory;
        CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);
        INSERT INTO inventory (name, quantity) VALUES ('banana', 150);
        INSERT INTO inventory (name, quantity) VALUES ('orange', 154);
        INSERT INTO inventory (name, quantity) VALUES ('apple', 100);
    `;

    client
        .query(query)
        .then(() => {
            console.log('Table created successfully!');
            client.end(console.log('Closed client connection'));
        })
        .catch(err => console.log(err))
        .then(() => {
            console.log('Finished execution, exiting now');
            process.exit();
        });
}

データの読み取り

接続し、SELECT SQL ステートメントを使用してデータを読み取るには、次のコードを使用します。 PostgreSQL サーバーとのインターフェイスには、pg.Client オブジェクトを使用します。 サーバーへの接続を確立するには、pg.Client.connect() 関数を使用します。 PostgreSQL データベースに対して SQL クエリを実行するには、pg.Client.query() 関数を使用します。

host、dbname、user、password の各パラメーターは、サーバーとデータベースの作成時に指定した値に置き換えてください。

const pg = require('pg');

const config = {
    host: '<your-db-server-name>.postgres.database.azure.com',
    // Do not hard code your username and password.
    // Consider using Node environment variables.
    user: '<your-db-username>',     
    password: '<your-password>',
    database: '<name-of-database>',
    port: 5432,
    ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
    if (err) throw err;
    else { queryDatabase(); }
});

function queryDatabase() {

    console.log(`Running query to PostgreSQL server: ${config.host}`);

    const query = 'SELECT * FROM inventory;';

    client.query(query)
        .then(res => {
            const rows = res.rows;

            rows.map(row => {
                console.log(`Read: ${JSON.stringify(row)}`);
            });

            process.exit();
        })
        .catch(err => {
            console.log(err);
        });
}

データの更新

接続し、UPDATE SQL ステートメントを使用してデータを読み取るには、次のコードを使用します。 PostgreSQL サーバーとのインターフェイスには、pg.Client オブジェクトを使用します。 サーバーへの接続を確立するには、pg.Client.connect() 関数を使用します。 PostgreSQL データベースに対して SQL クエリを実行するには、pg.Client.query() 関数を使用します。

host、dbname、user、password の各パラメーターは、サーバーとデータベースの作成時に指定した値に置き換えてください。

const pg = require('pg');

const config = {
    host: '<your-db-server-name>.postgres.database.azure.com',
    // Do not hard code your username and password.
    // Consider using Node environment variables.
    user: '<your-db-username>',     
    password: '<your-password>',
    database: '<name-of-database>',
    port: 5432,
    ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
    if (err) throw err;
    else {
        queryDatabase();
    }
});

function queryDatabase() {
    const query = `
        UPDATE inventory 
        SET quantity= 1000 WHERE name='banana';
    `;

    client
        .query(query)
        .then(result => {
            console.log('Update completed');
            console.log(`Rows affected: ${result.rowCount}`);
        })
        .catch(err => {
            console.log(err);
            throw err;
        });
}

データの削除

接続し、DELETE SQL ステートメントを使用してデータを削除するには、次のコードを使用します。 PostgreSQL サーバーとのインターフェイスには、pg.Client オブジェクトを使用します。 サーバーへの接続を確立するには、pg.Client.connect() 関数を使用します。 PostgreSQL データベースに対して SQL クエリを実行するには、pg.Client.query() 関数を使用します。

host、dbname、user、password の各パラメーターは、サーバーとデータベースの作成時に指定した値に置き換えてください。

const pg = require('pg');

const config = {
    host: '<your-db-server-name>.postgres.database.azure.com',
    // Do not hard code your username and password.
    // Consider using Node environment variables.
    user: '<your-db-username>',     
    password: '<your-password>',
    database: '<name-of-database>',
    port: 5432,
    ssl: true
};

const client = new pg.Client(config);

client.connect(err => {
    if (err) {
        throw err;
    } else {
        queryDatabase();
    }
});

function queryDatabase() {
    const query = `
        DELETE FROM inventory 
        WHERE name = 'apple';
    `;

    client
        .query(query)
        .then(result => {
            console.log('Delete completed');
            console.log(`Rows affected: ${result.rowCount}`);
        })
        .catch(err => {
            console.log(err);
            throw err;
        });
}

リソースをクリーンアップする

このクイックスタートで使用したすべてのリソースをクリーンアップするには、次のコマンドを使用してリソース グループを削除します。

az group delete \
    --name $AZ_RESOURCE_GROUP \
    --yes

次のステップ