gpt4 book ai didi

node.js - pg-promise 使用 $() 插入文本

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:18 24 4
gpt4 key购买 nike

当文本包含字符串“$(...)”时,我无法将文本插入数据库因为我的代码返回错误:属性“...”不存在。

const pgp = require('pg-promise')({ promiseLib: bluebird });
const db = pgp(process.env.DATABASE_URL);
let values = [{text: 'this is fine'}, {text: 'this fails $(...)'}];
let cs = new pgp.helpers.ColumnSet(['text']);
let query = pgp.helpers.insert(values, cs);
db.manyOrNone(query);

我是否缺少某种“这只是文本”属性?

谢谢

编辑只有在使用 $() 语法将其他变量添加到整个 SQL 调用时才会发生错误

'use strict';
const bluebird = require('bluebird');
const pgp = require('pg-promise')({ promiseLib: bluebird });
const db = pgp('postgres://localhost/okeydokey-local');

db.any(
'CREATE TABLE text_table ( ' +
'text_column text ' +
')'
);
let values = [{ text_column: 'this is fine' }, { text_column: 'this fails $(test)' }];
let cs = new pgp.helpers.ColumnSet(['text_column'], {table: 'text_table'});
let query = pgp.helpers.insert(values, cs);
console.log(query);
db.manyOrNone(query +
'some more SQL dependent on $(somethingElse)',
{
somethingElse: 'someValue'
}
);

输出

insert into "text_table"("text_column") values('this is fine'),('this fails $(test)')
Unhandled rejection Error: Property 'test' doesn't exist.

最佳答案

以下行生成您的最终查询:

let query = pgp.helpers.insert(values, cs);
//=>insert into "text_table"("text_column") values('this is fine'),('this fails $(test)')

它不是进一步格式化的查询模板,应该直接执行。

在您的代码中,您尝试格式化最终查询字符串,这会中断尝试在您的格式化对象中定位属性 test

关于node.js - pg-promise 使用 $() 插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39492889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com