Nodejs驱动使用说明
==============================

- 连接数据库_
- 执行语句_
- 关闭连接_

连接数据库
---------------------

使用 Client.connect() 连接数据库。

.. code:: PROGRAMLISTING

  const { Client } = require('kb')      /* 导入Nodejs驱动模块 */

  /* 实例化Client对象 */
  const client = new Client({
      user: 'SYSTEM',                  /* 用户名 */
      host: '192.168.0.102',           /* 数据库服务器的地址，包括域名、主机名、主机的 IP 地址等 */
      database: 'TEST',                /* 要连接的库 */ 
      password: '123456',              /* 密码 */ 
      port: 54321,                     /* 端口 */ 
      ssl: false,                      /* 是否使用ssl加密，true/false ，默认值为false */
  })

  /* 连接数据库 */
  client.connect(err => {
    if (err) {
      console.error('connection error', err.stack)
    } else {
      console.log('connected')
    }
  })

执行语句
---------------------

使用 Client.query() 执行语句。

a. 执行不带参数的语句

  .. code:: PROGRAMLISTING

     client.query('SELECT * FROM TEST', (err, res) => {
       if (err) throw err
       console.log(res)
     })

b. 执行带参数的语句     

  方法1:

  .. code:: PROGRAMLISTING

     const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
     const values = ['myname', 'myemail@gmail.com']
     /*  回调函数 */
     client.query(text, values, (err, res) => {
       if (err) {
         console.log(err.stack)
       } else {
         console.log(res)
       }
     })
   
  
  方法2:

  .. code:: PROGRAMLISTING

     const query = {
       text: 'INSERT INTO users(name, email) VALUES($1, $2)',
       values: ['myname', 'myemail@gmail.com'],
     }
     /*  回调函数 */
     client.query(query, (err, res) => {
       if (err) {
         console.log(err.stack)
       } else {
         console.log(res)
       }
     })

c. 创建一个准备好的语句,在多次执行时提高效率

  .. code:: PROGRAMLISTING

     const query = {
       /*  name参数用于命名准备好的语句 */
       name: 'fetch-user',
       text: 'SELECT * FROM user WHERE id = $1',
       values: [1],
     }
     /*  回调函数 */
     client.query(query, (err, res) => {
       if (err) {
         console.log(err.stack)
       } else {
         console.log(res)
       }
     })

关闭连接
---------------------------

使用 Client.end() 关闭连接。

.. code:: PROGRAMLISTING

  client.end(err => {
    console.log('client has disconnected')
    if (err) {
      console.log('error during disconnection', err.stack)
    }
  })

