企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Node Postgres 教程 > 原文: [http://zetcode.com/javascript/nodepostgres/](http://zetcode.com/javascript/nodepostgres/) Node Postgres 教程展示了如何通过`node-postgres`在 JavaScript 中使用 PostgreSQL 数据库。 ## Node postgres `node-postgres`是 Node.js 模块的集合,用于与 PostgreSQL 数据库接口。 它支持回调,promise,异步/等待,连接池,准备好的语句,游标和流式结果。 在我们的示例中,我们还使用 Ramda 库。 有关更多信息,请参见 [Ramda 教程](/javascript/ramda/)。 ## 安装`node-postgres` 首先,我们安装`node-postgres`。 ```js $ node -v v11.5.0 ``` 我们使用 Node 版本 11.5.0。 ```js $ npm init -y ``` 我们启动一个新的 Node 应用。 ```js $ npm i pg ``` 我们使用`nmp i pg`安装 node-postgres。 ```js $ npm i ramda ``` 另外,我们安装 Ramda 来处理数据。 `cars.sql` ```js DROP TABLE IF EXISTS cars; CREATE TABLE cars(id SERIAL PRIMARY KEY, name VARCHAR(255), price INT); INSERT INTO cars(name, price) VALUES('Audi', 52642); INSERT INTO cars(name, price) VALUES('Mercedes', 57127); INSERT INTO cars(name, price) VALUES('Skoda', 9000); INSERT INTO cars(name, price) VALUES('Volvo', 29000); INSERT INTO cars(name, price) VALUES('Bentley', 350000); INSERT INTO cars(name, price) VALUES('Citroen', 21000); INSERT INTO cars(name, price) VALUES('Hummer', 41400); INSERT INTO cars(name, price) VALUES('Volkswagen', 21600); ``` 在某些示例中,我们使用此`cars`表。 ## `node-postgres`第一个示例 在第一个示例中,我们连接到 PostgreSQL 数据库并返回一个简单的`SELECT`查询结果。 `first.js` ```js const pg = require('pg'); const R = require('ramda'); const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; const client = new pg.Client(cs); client.connect(); client.query('SELECT 1 + 4').then(res => { const result = R.head(R.values(R.head(res.rows))); console.log(result); }).finally(() => client.end()); ``` 该示例连接到数据库并发出`SELECT`语句。 ```js const pg = require('pg'); const R = require('ramda'); ``` 我们包括`pg`和`ramda`模块。 ```js const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; ``` 这是 PostgreSQL 连接字符串。 它用于建立与数据库的连接。 ```js const client = new pg.Client(cs); client.connect(); ``` 创建一个客户端。 我们使用`connect()`连接到数据库。 ```js client.query('SELECT 1 + 4').then(res => { const result = R.head(R.values(R.head(res.rows))); console.log(result); }).finally(() => client.end()); ``` 我们发出一个简单的`SELECT`查询。 我们得到结果并将其输出到控制台。 `res.rows`是一个对象数组; 我们使用 Ramda 来获取返回的标量值。 最后,我们使用`end()`关闭连接。 ```js $ node first.js 5 ``` 这是输出。 ## `node-postgres`列名称 在下面的示例中,我们获取数据库的列名称。 `column_names.js` ```js const pg = require('pg'); const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; const client = new pg.Client(cs); client.connect(); client.query('SELECT * FROM cars').then(res => { const fields = res.fields.map(field => field.name); console.log(fields); }).catch(err => { console.log(err.stack); }).finally(() => { client.end() }); ``` 列名使用`res.fields`属性检索。 我们还使用`catch`子句输出潜在的错误。 ```js $ node column_names.js [ 'id', 'name', 'price' ] ``` 输出显示`cars`表的三个列名称。 ## 选择所有行 在下一个示例中,我们从数据库表中选择所有行。 `all_rows.js` ```js const pg = require('pg'); const R = require('ramda'); const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; const client = new pg.Client(cs); client.connect(); client.query('SELECT * FROM cars').then(res => { const data = res.rows; console.log('all data'); data.forEach(row => { console.log(`Id: ${row.id} Name: ${row.name} Price: ${row.price}`); }) console.log('Sorted prices:'); const prices = R.pluck('price', R.sortBy(R.prop('price'), data)); console.log(prices); }).finally(() => { client.end() }); ``` 该示例输出`cars`表中的所有行以及汽车价格的排序列表。 ```js $ node all_rows.js all data Id: 1 Name: Audi Price: 52642 Id: 2 Name: Mercedes Price: 57127 Id: 3 Name: Skoda Price: 9000 Id: 4 Name: Volvo Price: 29000 Id: 5 Name: Bentley Price: 350000 Id: 6 Name: Citroen Price: 21000 Id: 7 Name: Hummer Price: 41400 Id: 8 Name: Volkswagen Price: 21600 Sorted prices: [ 9000, 21000, 21600, 29000, 41400, 52642, 57127, 350000 ] ``` 这是输出。 ## `node-postgres`参数化查询 参数化查询使用占位符,而不是直接将值写入语句。 参数化查询可提高安全性和性能。 `parameterized.js` ```js const pg = require('pg'); const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; const client = new pg.Client(cs); client.connect(); const sql = 'SELECT * FROM cars WHERE price > $1'; const values = [50000]; client.query(sql, values).then(res => { const data = res.rows; data.forEach(row => console.log(row)); }).finally(() => { client.end() }); ``` 该示例在简单的`SELECT`语句中使用参数化查询。 ```js const sql = 'SELECT * FROM cars WHERE price > $1'; ``` 这是`SELECT`查询。 `$1`是一个占位符,以后会以安全的方式替换为一个值。 ```js const values = [50000]; ``` 这些是要插入到参数化查询中的值。 ```js client.query(sql, values).then(res => { ``` 这些值作为第二个参数传递到`query()`方法。 ```js $ node parameterized.js { id: 1, name: 'Audi', price: 52642 } { id: 2, name: 'Mercedes', price: 57127 } { id: 5, name: 'Bentley', price: 350000 } ``` 这是输出。 ## 使用`async/await`的`node-postgres` Node Postgres 支持`async/await`语法。 `async_await.js` ```js const pg = require('pg'); const R = require('ramda'); const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; async function fetchNow() { const client = new pg.Client(cs); try { await client.connect(); let result = await client.query('SELECT now()'); return R.prop('now', R.head(result.rows)); } finally { client.end() } } fetchNow().then(now => console.log(now)); ``` 该示例使用`async/await`输出`SELECT now()`查询的结果。 ```js $ node async_await.js 2019-02-17T11:53:01.447Z ``` 这是输出。 ## `node-postgres`行模式 默认情况下,`node-postgres`将数据作为对象数组返回。 我们可以告诉`node-postgres`以数组的形式返回数据。 `row_mode.js` ```js const pg = require('pg'); const R = require('ramda'); const cs = 'postgres://postgres:s$cret@localhost:5432/ydb'; const client = new pg.Client(cs); client.connect(); const query = { text: 'SELECT * FROM cars', rowMode: 'array' }; client.query(query).then(res => { const data = res.rows; console.log('all data'); data.forEach(row => { console.log(`Id: ${row[0]} Name: ${row[1]} Price: ${row[2]}`); }) console.log('Sorted prices:'); const prices = data.map(x => x[2]); const sorted = R.sort(R.comparator(R.lt), prices); console.log(sorted); }).finally(() => { client.end() }); ``` 该示例显示`cars`表中的所有行。 它启用数组行模式。 ```js const query = { text: 'SELECT * FROM cars', rowMode: 'array' }; ``` 我们使用将`rowMode`设置为`array`的配置对象。 ```js console.log('all data'); data.forEach(row => { console.log(`Id: ${row[0]} Name: ${row[1]} Price: ${row[2]}`); }) ``` 现在我们遍历数组数组。 ```js $ node row_mode.js all data Id: 1 Name: Audi Price: 52642 Id: 2 Name: Mercedes Price: 57127 Id: 3 Name: Skoda Price: 9000 Id: 4 Name: Volvo Price: 29000 Id: 5 Name: Bentley Price: 350000 Id: 6 Name: Citroen Price: 21000 Id: 7 Name: Hummer Price: 41400 Id: 8 Name: Volkswagen Price: 21600 Sorted prices: [ 9000, 21000, 21600, 29000, 41400, 52642, 57127, 350000 ] ``` 这是输出。 ## `node-postgres`池化示例 连接池可提高数据库应用的性能。 它是特别有用的 Web 应用。 `pooled.js` ```js const pg = require('pg'); var config = { user: 'postgres', password: 's$cret', database: 'ydb' } const pool = new pg.Pool(config); pool.connect() .then(client => { return client.query('SELECT * FROM cars WHERE id = $1', [1]) .then(res => { client.release(); console.log(res.rows[0]); }) .catch(e => { client.release(); console.log(e.stack); }) }).finally(() => pool.end()); ``` 该示例说明如何设置一个使用连接池的示例。 完成查询后,我们将调用`client.release()`方法将连接返回到池。 ```js }).finally(() => pool.end()); ``` `pool.end()`耗尽所有活动客户端的池,断开它们的连接,并关闭该池中的所有内部计时器。 在此示例的脚本中使用了此方法。 在 Web 应用中,我们可以在 Web 服务器关闭或根本不调用时调用它。 在本教程中,我们使用`node-postgres`与 Node.js 中的 PostgreSQL 进行交互。 您可能也对以下相关教程感兴趣: [Knex.js 教程](/javascript/knex/), [Sequelize 教程](/javascript/sequelize/),[从 JavaScript 中的 URL 读取 JSON](/articles/javascriptjsonurl/) , [JavaScript 贪食蛇教程](/javascript/snake/) , [JQuery 教程](/web/jquery/), [Node Sass 教程](/javascript/nodesass/), [Lodash 教程](/javascript/lodash/)。