Node.js 与 PostgreSQL 集成:深入 pg 模块的应用与实践
title: Node.js 与 PostgreSQL 集成:深入 pg 模块的应用与实践
npm install pg
const { Pool } = require('pg');
// 创建数据库连接池
const pool = new Pool({
user: 'your_user',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
// 测试连接
pool.connect()
.then(client => {
console.log('成功连接到数据库');
client.release(); // 释放客户端连接
})
.catch(err => console.error('连接失败', err));
// 执行查询并获取结果
const fetchData = async () => {
const client = await pool.connect();
try {
const res = await client.query('SELECT * FROM your_table');
console.log(res.rows); // 打印查询结果
} catch (err) {
console.error(err);
} finally {
client.release(); // 释放客户端连接
}
};
fetchData();
const insertData = async () => {
const client = await pool.connect();
const insertQuery = 'INSERT INTO your_table(column1, column2) VALUES($1, $2) RETURNING *';
const values = ['value1', 'value2'];
try {
const res = await client.query(insertQuery, values);
console.log('插入成功:', res.rows[0]);
} catch (err) {
console.error('插入失败:', err);
} finally {
client.release();
}
};
insertData();
const performTransaction = async () => {
const client = await pool.connect();
try {
await client.query('BEGIN'); // 开始事务
const insertQuery = 'INSERT INTO your_table(column1) VALUES($1)';
await client.query(insertQuery, ['value1']);
// 条件判断,可以选择是否提交或回滚
if (someCondition) {
await client.query('COMMIT'); // 提交事务
console.log('事务提交成功');
} else {
await client.query('ROLLBACK'); // 回滚事务
console.log('事务被回滚');
}
} catch (err) {
await client.query('ROLLBACK'); // 发生错误进行回滚
console.error('事务失败:', err);
} finally {
client.release();
}
};
performTransaction();
const processStream = async () => {
const client = await pool.connect();
const query = client.query(new Query('SELECT * FROM large_table'));
query.on('row', row => {
console.log('Row:', row);
});
query.on('end', () => {
console.log('查询处理完毕');
client.release();
});
query.on('error', err => {
console.error('查询出错:', err);
client.release();
});
};
processStream();
const handleErrors = async () => {
const client = await pool.connect();
try {
await client.query('SELECT * FROM non_existing_table');
} catch (err) {
if (err.code === '42P01') { // 表不存在的错误码
console.error('错误: 表不存在!');
} else {
console.error('数据库错误:', err);
}
} finally {
client.release();
}
};
handleErrors();
const { Client } = require('pg');
const { DataFrame } = require('node-pandas'); // 假设使用一个类似 pandas 的库
const fetchAndAnalyzeData = async () => {
const client = new Client({
user: 'your_user',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
await client.connect();
try {
const res = await client.query('SELECT * FROM your_table');
const df = new DataFrame(res.rows);
// 对数据进行分析
console.log(df.describe());
} finally {
await client.end();
}
};
fetchAndAnalyzeData();
const express = require('express');
const { Pool } = require('pg');
const app = express();
const pool = new Pool({
user: 'your_user',
host: 'localhost',
database: 'your_database',
password: 'your_password',
port: 5432,
});
// 获取数据的 API 路由
app.get('/api/data', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM your_table');
res.json(result.rows); // 返回查询结果
} catch (err) {
console.error('查询失败:', err);
res.status(500).send('服务器错误');
}
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器正在监听 ${PORT}`);
});
评论
发表评论