mysql - 尝试在 Node 中批量插入用户数组时出现问题

标签 mysql node.js npm

我花了很多时间查看有关如何使用 Node 进行批量插入的所有解决方案(特别是 hereherehere ),但我仍然无法从用户列表中插入多行。

我的数组如下所示:

[ [ 'user 1' ], [ 'user 2' ], [ 'user3' ] ]

我的代码如下:

let insert_sql = "INSERT IGNORE INTO followers (username) VALUES (?)"
  await connection.execute(insert_sql, [users], function (err, result) {
    if (err) throw err
    console.log("Number of records inserted: " + result.affectedRows)
  })

但它只将所有用户插入一行...... 我正在使用 npm 和 mysql2 包,这可能是问题的根源吗?

最佳答案

您需要更改为 .query() ,以便在客户端构建更长的查询,或者使用 .execute 并将插入数据序列化到/来自单个参数(例如,使用 JSON 字段和存储过程)或在查询文本中使用匹配数量的占位符let insert_sql = "INSERT IGNORE INTO followers (username) VALUES (?, ?, ?)";等待连接.执行(insert_sql,[用户])

这是我的 answer解释执行与查询之间的区别“为什么 IN ?不执行时发出警告?”问题:

.execute() under the hood is doing prepare + execute commands

query vs execute step by step:

query:

format sql on the client: 'SELECT id FROM mytable WHERE id IN (?)' + [ [1,2,3] ] becomes 'SELECT id FROM mytable WHERE id IN (1, 2, 3)' send COM_QUERY command with 'SELECT id FROM mytable WHERE id IN (1, 2, 3)' read fields + rows execute:

send COM_PREPARE command with SELECT id FROM mytable WHERE id IN (?) as query parameter read prepared statement result (id + parameters + result fields if known from query ). For this query there is one parameter ( one ? ). id is a number, usually starts with 1 for every connection ( not unique server-wise, you can't prepare statement in one connection and use in another ) send COM_EXECUTE command using statement id + parameters. Parameters must be simple mysql types, and currently all parameters coerced to strings and serialised as strings (with exception for Buffer parameters, they sent as is). In your example is "please execute stmt with id 1 and one parameter which is a string "1,2,3" Result from prepare step above is cached, with next execute commands with same query only 'COM_EXECUTE' part is performed

I agree that this is confusing but this is how prepared statement work. We should improve this with better documentation and maybe some parameter validation warnings/errors like _"hey, are you sure you want to send your {foo: 'bar'} parameter to prepared statement? It'll be sent as [Object object]!''

关于mysql - 尝试在 Node 中批量插入用户数组时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54178477/

相关文章:

mysql - 如何在mysql中获取触发器中的过程输入参数

mysql - 如何修复 MySQL 中这个简单的外键错误

javascript - 使用 ajax 和查询进行实时搜索引导

javascript - 在 nodejs 中的 postgres 中保存记录之前,对象 js 模型字段数据 trim

javascript - 如何将 moment js 日期时间转换为字符串,反之亦然

node.js - 抛出新错误 ('Missing PFX or certificate + private key' )

node.js - npm install 和 npm install --save 之间的区别?

mysql - 如何从mysql表中每次选择50行

javascript - 如何在一个 gulp 任务中运行多个操作?

macos - 错误 : The 'brew link' step did not complete successfully