@JunQiu
2018-09-25T01:57:34.000000Z
字数 1581
阅读 1396
summary_2018/09 pgsql
// const Client = require('pg').Client// 我们应该会使用连接池的方式,连接会自动断开,linux下两个小时const Pool = require('pg').Pool/*默认连接可以下面配置变量,其它可以参考文档:PGHOST=process.env.HOSTPGUSER=process.env.USER当然也可以自己配置:const pool = new Pool({user: 'dbuser',host: 'database.server.com',database: 'mydb',password: 'secretpassword',port: 3211,})不过我们应该会使用:connectionStringpostgres://someuser:somepassword@somehost:381/somedatabase*/const connectionString = 'postgresql://postgres:123456@localhost:5432/postgres'async function mian () {// const client = new Client()// pool和Client的方式API相同,只是机制不同const pool = new Pool({connectionString})// 插入操作,操作为规范的SQL,防止SQL注入我们会使用Parameterized query// 推荐query object的方式const insertQuery = {text: 'insert into test(name, age,grad) values($1, $2,$3)',values: ['b', '3', 'B'],}// jsonb dataType,node可以尝试这种方式,可以对jsonb建立索引,插入object会简单一些const jsonb = {test: '0',test1: '1'}// 感觉多行操作比较麻烦需要拼接const insertMany = {text: 'insert into test(name, age, grad, js) values($1,$2,$3,$4),($5,$6,$7,$8)',values: ['b', '3', 'D', jsonb, 'e', '3', 'F', jsonb],}const updatetQuery = 'update test set age = 33 where name = \'a\''const delQuery = 'delete from test where age = 2'const selectQuery = {text: 'select * from test',// 每行以数组的方式返回,默认object(使用 JSON.parse 将服务器上的 json 转为 js 的json)rowMode: 'array'}await pool.query(insertQuery)await pool.query(insertMany)await pool.query(updatetQuery)await pool.query(delQuery)// node-postgres will convert a database type to a JavaScript string if it doesn't have a registered type parser for the database type.const res = await pool.query(selectQuery)console.log(res.rows)// close connectionawait pool.end()}mian().catch(err => console.log(err))
