2017-09-30 10 views
0

たとえば、次のコード(node-postgresを使用)では、クライアントに接続し、クエリを実行して終了します。ウェブフロントエンドからデータベースに接続する最も速い方法は何ですか?

const { Pool, Client } = require('pg') 

const pool = new Pool({ 
    user: 'dbuser', 
    host: 'database.server.com', 
    database: 'mydb', 
    password: 'secretpassword', 
    port: 3211, 
}) 

pool.query('SELECT NOW()', (err, res) => { 
    console.log(err, res) 
    pool.end() 
}) 

const client = new Client({ 
    user: 'dbuser', 
    host: 'database.server.com', 
    database: 'mydb', 
    password: 'secretpassword', 
    port: 3211, 
}) 
client.connect() 

client.query('SELECT NOW()', (err, res) => { 
    console.log(err, res) 
    client.end() 
}) 

データベースを照会するたびに接続を作成する必要がありますか?より速い方法がありますか?

node-postgres以外のものを使用することをおすすめしますか?

答えて

1

ORMを続けることをお勧めしますので、他のデータベース操作について心配する必要はありません。また、PostgreSQLをサポートし、接続を維持して終了します。接続を作成するだけで、Sequelizeはあなたのために残っています。素晴らしいです。

Sequelizeは、Node.js v4以降の約束ベースのORMです。 PostgreSQL、MySQL、SQLite、MSSQLなどの方言をサポートし、トランザクションのサポート、リレーションシップ、レプリケーションの読み取りなどをサポートしています。

const sequelize = new Sequelize('database', 'username', 'password', { 
    host: 'localhost', 
    dialect: 'mysql'|'sqlite'|'postgres'|'mssql', 

    pool: { 
    max: 5, 
    min: 0, 
    idle: 10000 
    }, 

    // SQLite only 
    storage: 'path/to/database.sqlite' 
}); 

// Or you can simply use a connection uri 
const sequelize = new Sequelize('postgres://user:[email protected]:5432/dbname'); 

あなたは、接続をテストするには、このよう.authenticate()機能を使用することができます。詳細については

sequelize 
    .authenticate() 
    .then(() => { 
    console.log('Connection has been established successfully.'); 
    }) 
    .catch(err => { 
    console.error('Unable to connect to the database:', err); 
    }); 

http://docs.sequelizejs.com/

関連する問題