【问题标题】:Incorrect syntax for insert query插入查询的语法不正确
【发布时间】:2018-09-25 15:52:59
【问题描述】:

我正在使用 JavaScript 和 PostgreSQL,我想知道代码和语法是否正确编写,因为我在不同的情况下会遇到奇怪的错误。

例子:

function putDbEvents({ description, creatorId, attendeeId }) {
  return pool
    .query(`INSERT INTO events (${description}, ${creatorId}), ${attendeeId}`)
    .then(() => pool.end())
    .catch(console.log);
}

我的问题:

  1. 应该是{}在函数的第一行吗?我认为只有 ()?
  2. 应该是这样插入还是这样 INSERT INTO events ('description', creatorId, attendeeId) VALUES then (${}...

这是建表代码:

const createEventsRes = await pool.query(
  "CREATE TABLE IF NOT EXISTS events (id serial PRIMARY KEY, description TEXT, creatorId INTEGER, attendeeId INTEGER)"
);

我想创建一个表,所以每次添加内容时,它都应该自动添加一个 id,你只需将描述、id、id 传递给它,第四个是可选的,因此在这种情况下不需要,并且想看看如果语法正确。

【问题讨论】:

标签: javascript sql database postgresql syntax


【解决方案1】:

插入时需要给列命名:

INSERT INTO events (description, creatorid, attendeeid) 
  values (${description}, ${creatorId}), ${attendeeId})

这是一个很好的做法。当您省略列时也需要它(在这种情况下为id)。

【讨论】:

  • 是否也应该和`一起使用? ` 像这样:并且它也应该是 () 内的 {} 吗? function putDbEvents({ description, creatorId, AttendeeId }) { return pool .query(INSERT INTO events (description, creatorid, attendeeid) values (${description}, ${creatorId} ${attendeeId}) .then(() => pool.end()) .catch(console.log); }
【解决方案2】:

Nvm,我解决了。

function putDbEvents(description, creatorid, Attendeeid) { 返回池 .query(INSERT INTO events (description, creatorid, attendeeid) values ($1, $2, $3), [描述, 创建者 ID, 参加者 ID]) .then(() => pool.end()) .catch(console.log); }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2021-12-09
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多