1

我正在尝试将我的旧 mysql 应用程序转换为 Postgresql,连接到服务器非常困难,但是当我认为它有效时,此消息出现在失眠症上。 我尝试使用在 Google 上找到的不同方法的消息 ,但它们对我不起作用。我认为问题在于我如何连接到服务器。我是使用 postgresql 的新手。

const { Pool, Client } = require("pg")

const config = require("../config")

const connection = new Pool({
  host: config.postgresql.host,
  user: config.postgresql.user,
  password: config.postgresql.password,
  database: config.postgresql.database,
  port: "5432",
  ssl: true
})

function list(table) {
  return new Promise((resolve, reject) => {
    connection.query(`SELECT * FROM ${table}`, (err, data) => {
      if (err) return reject(err)
      resolve(data)
    })
  })
}

function get(table, id) {
  return new Promise((resolve, reject) => {
    connection.query(`SELECT * FROM ${table} WHERE id=${id}`, (err, data) => {
      if (err) return reject(err)
      resolve(data)
    })
  })
}

function insert(table, data) {
  return new Promise((resolve, reject) => {
    connection.query(`INSERT INTO ${table} SET ${data}`, (err, result) => {
      if (err) return reject(err)
      resolve(result)
    })
  })
}

function update(table, data) {
  return new Promise((resolve, reject) => {
    connection.query(
      `UPDATE ${table} SET ${data} WHERE id=${data.id}`,
      (err, result) => {
        if (err) return reject(err)
        resolve(result)
      }
    )
  })
}

const upsert = async (table, payload) =>
  new Promise((resolve, reject) => {
    connection.query(
      `INSERT INTO ${table} SET ${payload} ON DUPLICATE KEY UPDATE ${payload}`,
      (error, data) => {
        console.log("UPDATE DATA: ", data)
        if (error) {
          return reject(error)
        }
        resolve(data)
      }
    )
  })

function query(table, query, join) {
  let joinQuery = ""
  if (join) {
    const key = Object.keys(join)[0]
    const val = join[key]
    joinQuery = `JOIN ${key} ON ${table}.${val} = ${key}.id`
  }

  return new Promise((resolve, reject) => {
    connection.query(
      `SELECT * FROM ${table} ${joinQuery} WHERE ${table}.${query}`,
      (err, res) => {
        if (err) return reject(err)
        resolve(res[0] || null)
      }
    )
  })
}

module.exports = {
  list,
  get,
  upsert,
  query
}
4

1 回答 1

2

插入查询错误,请将其更改为以下语法。您不能SET在插入中使用。SET应该用在update.

错误的:

connection.query(`INSERT INTO ${table} SET ${data}`, (err, result) 

插入查询语法:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
于 2020-03-10T03:58:07.157 回答