<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # 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/)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看