Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将数组中的值插入表中_Javascript_Node.js_Database_Postgresql - Fatal编程技术网

Javascript 将数组中的值插入表中

Javascript 将数组中的值插入表中,javascript,node.js,database,postgresql,Javascript,Node.js,Database,Postgresql,我想将数组中的值插入表中 var theFields = "my_id,"+ "fruit,"+... var theData = [ my_id, req.body.fruit,... ] 我可以做到: client.query("INSERT INTO theTable("+ theFields +") values($1,$2,$3,$4,$5,$6,$7,$8,$9,...." + 但我想避免“1美元,2美元……等等” 所以,我试着:

我想将数组中的值插入表中

var theFields = 
    "my_id,"+ 
    "fruit,"+...

var theData = [
    my_id,
    req.body.fruit,...
     ]
我可以做到:

client.query("INSERT INTO theTable("+ theFields +") values($1,$2,$3,$4,$5,$6,$7,$8,$9,...." +
但我想避免“1美元,2美元……等等”

所以,我试着:

client.query("INSERT INTO theTable("+ theFields +")  values($1::varchar[])",[theData], function(err, result) {

client.query("INSERT INTO theTable("+ theFields +")  values ANY($1::varchar[])",[theData], function(err, result) {
但它们不起作用

请注意,字段的类型相同,varchar


(另外,如果我有不同的类型,有没有一种方法可以使用我正在尝试的解决方案来实现这一点?

您可以通过编程编写字符串
$1,$2,…
)。我假设数据数组的长度等于查询中的字段数:

var values = theData.map(function(f, i) {
    return "$" + (i + 1);
}).join();
client.query("INSERT INTO theTable(" + theFields + ")  values(" + values + ")", ...

这是一个坏主意,因为变量为字符串提供了适当的转义,还可以防止SQL注入。它给出了
TypeError:theFields.map不是一个函数
`:在查询中,在
值(“+values+”)之后,
是否应该有
值(“+values+”)、数据、函数(err,result){
[theData],函数(err,result){
或其他内容,因为它挂起。