【问题标题】:Best way pass array as query params for pg PoolClient with postgres using typescript使用 typescript 将数组作为带有 postgres 的 pg PoolClient 的查询参数传递的最佳方法
【发布时间】:2021-11-03 19:56:27
【问题描述】:

我正在使用 pg PoolClient 使用 typescript 从 postgres 数据库中获取一些数据,目前,我正在使用以下方式获取一些数据,如果有更好的方法可以实现,请告诉我

const SPECIAL_LIST = [
    "ABC",
    "XYZ",
    "PQR",
    "LMN",
    "EFG",
    "IJK",
  ];
var params = SPECIAL_LIST.reduce(function (a, b, idx) {
    if (idx === 0) return '$' + (idx + 2);
    else return a + ', $' + (idx + 2);
  }, '');
const sql = "Select sg.code,sg.dep,sg.vo,sg.arr from table1 sg where sg.is_omitted is false and v_code = $1 and sg.r_code not in (" +params+ ") order by sg.est_datetime asc"
  const values = [vesselCode].concat(SPECIAL_LIST);
  const client = await pool.connect();
  await client
    .query(sql, values)
    .then((res) => {
      const data = res.rows;
      console.log(res.rowCount)
      data.forEach((row) => {
        // function logic
      });
    })
    .catch((e) => console.error(e))
    .then(() => client.release());

【问题讨论】:

    标签: sql typescript postgresql


    【解决方案1】:

    使用以下任何方法找到解决方案就是解决方案

    const sql =
        `SELECT v1, v2, v3, v4, v5, v6, v7
        FROM ${TABLE_NAME}
        WHERE omitted IS FALSE
        AND v1 = $1
        AND NOT rcode = ANY ($2)
        ORDER BY datetime_dt ASC`;
      const values = [vCode, SPECIAL_SITES];
    
      const client = await pool.connect();
      await client
        .query({ text: sql, values: values })
        .then((res) => {
          res.rows.forEach((row) => {
            //......
          });
        })
        .catch((e) => console.error(e))
        .then(() => client.release());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多