转义 PostgreSQL 字符串值

Escape PostgreSQL string values

我正在尝试向我的 postgres 数据库中插入超过 70k 个值。但是,每一行都有不同类型的特殊字符。当我插入时,我得到了通常的错误。例如: syntax error at or near ".5"。我正在使用模块 pg-promise。在我使用的代码下方:

  function pg_insert(x) {
        var name = x["name"];
        var lastName = x["lasname"];

        var sql = `insert into table(name, lastname)`;
        var values = `values (${name},${lastname})`;

        pg.db
        .none(sql + values)
        .then(data => {})
        .catch(err => {
            console.log(err);
        });
    }

如有任何帮助,我们将不胜感激。

谢谢

如 Lukasz 所述,使用 Parameterized Query:

  function pg_insert(x) {
    const name = x['name'];
    const lastName = x['lasname'];

    const sql = 'insert into table(name, lastname) values (, )';
    const values = [name, lastname];

    pg.db
    .none(sql, values)
    .then(data => {})
    .catch(err => {
      console.log(err);
    });
  }

您也可以使用 Named Parameters:

  function pg_insert(x) {
    const sql = 'insert into table(name, lasname) values (${name}, ${lastname})';

    pg.db
    .none(sql, x)
    .then(data => {})
    .catch(err => {
      console.log(err);
    });
  }

不过,如pg-promise Named Parameters documentation所述:

Keep in mind that while property values null and undefined are both formatted as null, an error is thrown when the property does not exist.

如果您传递的对象 x 中的任何属性不存在 (例如 x.namex.lasname{ "name": "Joe" }(请注意缺少的 lasname 属性)),则上面的命名参数示例代码将产生错误。

正如 vitaly-t(库创建者)提到的,pg-promise 中有 helper methods 来帮助丢失数据。但是,如果您不能保证将传递到查询中的数据的形状,并且对添加清理数据所需的代码不感兴趣,那么参数化查询可能是更容易防止故障的选择。

留给 reader 来确定哪种方法最适合他们的用例。

如果您正确使用Named Parameters,那么它将起作用:

function pg_insert(x) {
    pg.db.none('INSERT INTO table(name, lastname) VALUES(${name}, ${lastname})', x)
    .then(data => {})
    .catch(err => {
        console.log(err);
    });
}

更新

我还修改了 official documentation 以包括以下内容:

WARNING: Never use ${} syntax inside ES6 template strings, as those have no knowledge of how to format values for PostgreSQL. Inside ES6 template strings you can only use one of the 4 alternatives - $(), $<>, $[] or $//.

...为了更清楚。