【问题标题】:Create insert function (postgresql) in node.js在 node.js 中创建插入函数(postgresql)
【发布时间】:2025-12-15 15:00:01
【问题描述】:

我正在尝试创建一个动态函数以在 node.js 中的 postgresql 数据库中插入值。我不想自己输入查询,而是想输入函数和参数,当我调用它时它会执行查询。

我想重新创建这个:

var query = "INSERT INTO my_table (id, fname) VALUES (3, 'Karees')"

我确信有一个正确的语法,但我不知道它是什么。所以我尝试像在 java 中的 System.out.print 中那样做。这就是说我的表是未定义的,如果我只是在查询中替换它就没有问题。我猜我的问题是变量引用。

我的代码:

function run(){
function insert(table, pkey, field, value){
    var query = "INSERT INTO "+ table +" ("+ pkey +", "+ field +") VALUES ('"+ value +"')"
    client.query(query, (err, res) => {
  console.log(err, res)
  client.end()
})
}
insert(my_table, 3, fname, Karees)
}

结果:

connected successfully
(node:1926828) UnhandledPromiseRejectionWarning: ReferenceError: my_table is not defined
    at run (C:\Users\Johnathan Aggrey\Documents\Job\IBVAZE TECH\Spark\conn.js:27:8)
    at client.connect.then.catch.finally (C:\Users\Johnathan Aggrey\Documents\Job\IBVAZE TECH\Spark\conn.js:12:16)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:1926828) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1926828) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

【问题讨论】:

  • "my_table 未定义"
  • my_table 是变量还是您的意思是将字符串 "my_table" 传递给函数?此外,您通常不希望通过连接变量来形成查询,尤其是当数据来自其他地方时。这使您面临 SQL 注入攻击。研究如何参数化查询。
  • 不是字符串,是我在数据库中的表名
  • 那么它应该是一个字符串。
  • 我把它改成了一个字符串,现在是说 { error: syntax error at or near "3"

标签: javascript node.js postgresql insert sql-insert


【解决方案1】:

在这一行中有几个值应该是字符串:

insert(my_table, 3, fname, Karees)

假设 my_table 是您的表的名称,fnameKarees 也是您想要在查询字符串中使用的值(而不是变量),您需要这样写:

insert('my_table', 3, 'fname', 'Karees')

【讨论】:

  • 我这样做了,现在它说连接成功{错误:“3”或附近的语法错误