正确准备pg查询的方法

时间:2018-04-01 17:08:15

标签: node.js database postgresql pg

我一直在尝试准备一个查询,以便为我使用Node js和npm包pg的某些用户更新表格中的行。运行查询时出现问题我的错误消息将返回错误:

  

语法错误在" VALUES"或" WHERE"

但从未提供更多错误的背景信息,难以确定。我尝试重新安排价值观并尝试不同的方法,但都没有成功。

populateProfileData(username, gender, dob, country, province, city, date, user_id) {
    console.log('================' + username + gender + dob + country + province + city + date + user_id);
    return new Promise(function (resolve, reject) {
        const client = new pg.Client(connectionString);
        client.connect()
            .then(() => console.log('connected'))
            .catch(err => console.error('connection error', err.stack))
        // This Works ---> UPDATE users SET dob = '032018' WHERE USER_id = 15
        const text = 'UPDATE users SET(username, dob, country, province, city, date)  WHERE user_id = (user_id) VALUES($1, $2, $3, $4, $5, $6, $7)';
        const values = [username, dob, country, province, city, date, user_id]
        const query = client.query(text, values)
            .then(success => {
                console.log('ran query')
                resolve(success);
            })
            .catch(error => {
                console.log('--------' + error)
                reject(error);
            })
    });
}
}

2 个答案:

答案 0 :(得分:1)

不知道该模块,但update语句的语法是这样的:

UPDATE users 
SET
  username = $1, 
  dob = $2, 
  country = $3, 
  province = $4, 
  city = $5, 
  date = $6
WHERE 
  user_id = $7

所以希望这会让你更接近工作代码

答案 1 :(得分:0)

  1. 对于更新某些记录,您必须将索引标识列[s]用于搜索现有行:
  2. INSERT INTO users (id, username, dob, country, province, city, date) 
    VALUES 
      (1, 'Joe', 1, 'usa', 'utah', 'odessa', '12-21-2015'),
      (2, 'Doe', 2, 'usa', 'utah', 'odessa', '12-21-2015'),
      ...
    ON CONFLICT (id)
    DO UPDATE SET 
      username=EXCLUDED.username,
      dob=EXCLUDED.dob,
      country=EXCLUDED.country,
      province=EXCLUDED.province,
      city=EXCLUDED.city,
      date=EXCLUDED.date;
    
    1. 而是更新您可以忽略的现有行:
    2. INSERT INTO users (id, username, dob, country, province, city, date) 
      VALUES 
        (1, 'Joe', 1, 'usa', 'utah', 'odessa', '12-21-2015'),
        (2, 'Doe', 2, 'usa', 'utah', 'odessa', '12-21-2015'),
        ...
      ON CONFLICT (id) 
      DO NOTHING
      
      1. 当您的表有约束时,您必须在更新前禁用它并在所有更新结束后打开:
      2. ALTER "country" DROP NOT NULL;
        INSERT INTO users (id, username, dob, country, province, city, date) 
        VALUES 
          (1, 'Joe', 1, 'usa', 'utah', 'odessa', '12-21-2015'),
          (2, 'Doe', 2, 'usa', 'utah', 'odessa', '12-21-2015'),
          ...
        ON CONFLICT (id)
        DO UPDATE SET 
          username=EXCLUDED.username,
          dob=EXCLUDED.dob,
          country=EXCLUDED.country,
          province=EXCLUDED.province,
          city=EXCLUDED.city,
          date=EXCLUDED.date;
        ALTER "country" SET NOT NULL;