如何使用节点postgres查询同步

时间:2017-11-04 17:59:06

标签: javascript postgresql

如何查询数据库中的行数并在while循环中传递它们?

# replace plyr with multidplyr
libs <- c("dplyr", "tidyr",'multidplyr')
devtools::install_github("hadley/multidplyr")
sapply(libs, require, character.only = T)

set.seed(1)
df <- data.frame(id = sample(1:10, 100000, TRUE), 
                 value = runif(100000))%>%as.tbl

# first the single core solution. No need to nest, 
# since group_by%>%do() automatically nests.
x<-df%>% 
  group_by(id)%>%
  # nest()%>%
  do(stat_summary=summary(.$value)%>%as.matrix%>%t%>%data.frame%>%as.tbl)%>%
  ungroup  

# next, multiple core solution
n_cores<-2
cl<-multidplyr::create_cluster(n_cores)
# you have to load the packages into each cluster
cluster_library(cl,c('dplyr','tidyr')) 
df_mp<-df%>%multidplyr::partition(cluster = cl,id) # group by id

x_mp<-df_mp%>% 
  do(stat_summary=summary(.$value)%>%as.matrix%>%t%>%data.frame%>%as.tbl)%>%
  collect()%>%
  ungroup

1 个答案:

答案 0 :(得分:0)

首先,您似乎使用“pg”库,因此无法进行同步查询,因为“pg”是非阻塞客户端。但可能你不需要它。在您的代码中,您使用async-await语法,这是使用此库的一种很好的异步方式,但您不需要回调来处理查询结果。 也许您的代码可能如下所示:

async function rows () {
  const res = await client.query('SELECT * FROM accounts WHERE proceeded = false')
  let i = 0
  while (i < 10) {
    console.log(res.rows[i])
    i++
  }
  await client.end()
}
rows()

或者更好的方式:

const { Pool } = require('pg')
const Cursor = require('pg-cursor')
const pool = new Pool()
const client = await pool.connect()
const query = 'SELECT * FROM accounts WHERE proceeded = false'
const cursor = client.query(new Cursor(query))

cursor.read(10, function (err, rows) => {
  if (err) throw err
  rows.forEach((row, i, arr) => console.log(row))
  cursor.close(() => {
    client.release()
  })
})

注意:我没有运行它,所以它只是一个示例。 您可以在https://node-postgres.com/

找到更多示例