例如,在以下代码中(使用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之外的其他内容?
答案 0 :(得分:1)
我会建议sequelize 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:pass@example.com:5432/dbname');
您可以使用此类.authenticate()
函数来测试连接。
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});