【问题标题】:How to append a dynamic string to a text type column in Postgres through Node.js?如何通过 Node.js 将动态字符串附加到 Postgres 中的文本类型列?
【发布时间】:2017-09-09 09:58:38
【问题描述】:

我正在尝试update Postgres from Node.js 中的 文本类型列。我想将 动态字符串 附加到文本类型列中的数据。

但我得到一个错误

“错误:无法确定参数$1的数据类型”

var pg = require('pg');

var connectionString = process.env.DATABASE_URL || "pg://admin:guest@localhost:5432/imagesearchexperiment";

var client = new pg.Client(connectionString);
client.connect();

client.query("DROP TABLE IF EXISTS imagesearchexperiment");
client.query("CREATE TABLE IF NOT EXISTS imagesearchexperiment(ipAddress varchar(64), searchqueries text)");

client.query("INSERT INTO imagesearchexperiment(ipAddress, searchqueries) VALUES($1, $2)",["ipAddress1","query1<>query2<>query3"]);
client.query("INSERT INTO imagesearchexperiment(ipAddress, searchqueries) VALUES($1, $2)",["ipAddress2","query1<>query2<>query3"]);
client.query("INSERT INTO imagesearchexperiment(ipAddress, searchqueries) VALUES($1, $2)",["ipAddress3","query1<>query2<>query3"]);

var searchQuery = "query4";
var ip = "ipAddress3";

// The following line is causing an error - error: could not determine data type of parameter $1
client.query("UPDATE imagesearchexperiment SET searchqueries = CONCAT($1, searchqueries) WHERE ipAddress = $2", [searchQuery, ip]);

我查看了以下链接。

如果我没有动态字符串,他们的解决方案可以工作。

  1. SQL Server - Adding a string to a text column (concat equivalent)
  2. How can I add text to SQL Column
  3. How to prepend a string to a column value in MySQL?
  4. How can I append a string to an existing field in MySQL?

请分享建议。谢谢:)

【问题讨论】:

  • 试试CONCAT($1::text, searchqueries) ;)
  • 如果你确定没有一个字符串是null,你可以使用$1 || searchqueries——这是因为CONCAT()使用generic paramaters(更具体地说是any)。因此,您始终必须使用查询解析器知道其类型的参数进行调用。您可以使用强制转换在 SQL 中实现这一点(如之前建议的那样),或者(通常)您可以通过绑定设置参数类型(在准备好的语句的情况下):但这在很大程度上取决于您的客户端库。
  • @vitaly-t 谢谢 :),现在可以使用了

标签: sql node.js postgresql


【解决方案1】:
UPDATE imagesearchexperiment SET searchqueries = '"+ searchqueries="' WHERE ipAddress = "'+ ip+'"

【讨论】:

    【解决方案2】:

    函数CONCAT 不确定它获得的数据类型。显式类型转换为 ::text 将有所帮助:

    CONCAT($1::text, searchqueries)
    

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 2019-10-17
      • 2021-10-04
      • 2014-02-25
      • 2021-09-06
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      相关资源
      最近更新 更多