[关闭]
@JunQiu 2018-09-25T01:57:34.000000Z 字数 1581 阅读 989

PG(use_idus)

summary_2018/09 pgsql


1、日常

1.1、PG操作


2、技术

2.1、PG操作

  1. // const Client = require('pg').Client
  2. // 我们应该会使用连接池的方式,连接会自动断开,linux下两个小时
  3. const Pool = require('pg').Pool
  4. /*
  5. 默认连接可以下面配置变量,其它可以参考文档:
  6. PGHOST=process.env.HOST
  7. PGUSER=process.env.USER
  8. 当然也可以自己配置:
  9. const pool = new Pool({
  10. user: 'dbuser',
  11. host: 'database.server.com',
  12. database: 'mydb',
  13. password: 'secretpassword',
  14. port: 3211,
  15. })
  16. 不过我们应该会使用:connectionString
  17. postgres://someuser:somepassword@somehost:381/somedatabase
  18. */
  19. const connectionString = 'postgresql://postgres:123456@localhost:5432/postgres'
  20. async function mian () {
  21. // const client = new Client()
  22. // pool和Client的方式API相同,只是机制不同
  23. const pool = new Pool({connectionString})
  24. // 插入操作,操作为规范的SQL,防止SQL注入我们会使用Parameterized query
  25. // 推荐query object的方式
  26. const insertQuery = {
  27. text: 'insert into test(name, age,grad) values($1, $2,$3)',
  28. values: ['b', '3', 'B'],
  29. }
  30. // jsonb dataType,node可以尝试这种方式,可以对jsonb建立索引,插入object会简单一些
  31. const jsonb = {
  32. test: '0',
  33. test1: '1'
  34. }
  35. // 感觉多行操作比较麻烦需要拼接
  36. const insertMany = {
  37. text: 'insert into test(name, age, grad, js) values($1,$2,$3,$4),($5,$6,$7,$8)',
  38. values: ['b', '3', 'D', jsonb, 'e', '3', 'F', jsonb],
  39. }
  40. const updatetQuery = 'update test set age = 33 where name = \'a\''
  41. const delQuery = 'delete from test where age = 2'
  42. const selectQuery = {
  43. text: 'select * from test',
  44. // 每行以数组的方式返回,默认object(使用 JSON.parse 将服务器上的 json 转为 js 的json)
  45. rowMode: 'array'
  46. }
  47. await pool.query(insertQuery)
  48. await pool.query(insertMany)
  49. await pool.query(updatetQuery)
  50. await pool.query(delQuery)
  51. // node-postgres will convert a database type to a JavaScript string if it doesn't have a registered type parser for the database type.
  52. const res = await pool.query(selectQuery)
  53. console.log(res.rows)
  54. // close connection
  55. await pool.end()
  56. }
  57. mian().catch(err => console.log(err))
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注