NODEJS将数据插入POSTGRESQL(错误:“ $”或附近的语法错误)

时间:2019-11-09 08:10:18

标签: node.js postgresql pg

我在nodejs中准备了语​​句,以便使用posgresql将数据插入数据库。我可以告诉我哪里出了问题,但是每一次我都会收到此错误(error: syntax error at or near "$"),请帮忙。

class Employees {
  constructor(user) {
    this.client = require("../database");
    this.createTable();
    // this.dropTable();
    this.bcrypt = require("bcrypt");
    this.user = user;
  }

  createTable() {
    this.client.query(
      "CREATE TABLE IF NOT EXISTS employees(userId SERIAL,firstName varchar(255) NOT NULL,lastName varchar(255) NOT NULL,email varchar(255) NOT NULL,password varchar(255) NOT NULL,gender varchar(255) NOT NULL,jobRole varchar(255) NOT NULL,department varchar(255) NOT NULL,address varchar(255) NOT NULL,PRIMARY KEY (userId))",
      (err, res) => {
        console.log("ERROR ==> " + err);
        console.log("RESPONSE ==> " + res);
      }
    );
  }

  // dropTable() {
  //     this.client.query("DROP TABLE employees", (err, res)=>{
  //         console.log("ERROR ==> " + err);
  //         console.log("RESPONSE ==> " + res);
  //     })
  // }

  // create employees and save into the databse
  async save() {
    this.bcrypt.hash(this.user.password, 10).then(hash => {
      // let sql = "INSERT INTO Teamwork.employees(userId,firstName,lastName,email,password,gender,jobRole,department,address) VALUES($fn, $ln, $em, $pwd, $gen, $job,$dep, $addr)";
      let params = [
        "",
        this.user.firstName,
        this.user.lastName,
        this.user.email,
        this.user.password,
        this.user.gender,
        this.user.jobRole,
        this.user.department,
        this.user.address
      ];

      this.client.query(
        "INSERT into employees (userId, firstName, lastName, email, password, gender, jobRole, department, address) VALUES($id, $1, $2, $3, $4, $5, $6, $7, $8) RETURNING userId",
        params,
        (err, res) => {
          console.log("ERROR ==> " + err);
          console.log("RESPONSE ==> " + res);
        }
      );

      // .catch( (error)=>{
      //     console.log(error);
      // })

      // .finally( ()=>this.client.end())
    });
  }
}

module.exports = Employees;

上面是我的代码段。

1 个答案:

答案 0 :(得分:1)

在插入语句中删除用户ID,因为该字段被标记为串行,因此不应包含在该语句中。