mysql2/promise: INSERT 语句在事务查询中无效

mysql2/promise: INSERT statement not valid in transaction query

感谢您的宝贵时间。我在使用 mysql2/promise 包创建交易查询时遇到问题。

查询如下:

    await db.execute(`START TRANSACTION`);
    await db.execute(`INSERT INTO user VALUES (?, ?, ?, ?, ?, ?)`, [...userDetails]);
    await db.execute(`INSERT INTO account VALUES (?, ?, ?, ?, ?, ?)`, [...accountDetails]);
    await db.execute(`COMMIT`);

这是我得到的错误:

Error: This command is not supported in the prepared statement protocol yet
code: 'ER_UNSUPPORTED_PS',
  errno: 1295,
  sql: 'START TRANSACTION',
  sqlState: 'HY000',
  sqlMessage: 'This command is not supported in the prepared statement protocol yet'

请问是否与我的查询有关?我相信 INSERT 语句在事务块中应该完全没问题。我也试过将每个查询组合成一个字符串,但这似乎也不起作用。

MySQL限制哪些语句可以在prepared statements中完成,start transaction是不允许的。参见 SQL Syntax Allowed In Prepared Statements and here is a demonstration

execute is always using and caching prepared statements。如果查询很复杂(MySQL 不必每次都解析它)或接受参数(为了安全),这很好。

但是,如果您的查询很简单且不带任何参数,则无需准备。使用仅运行 SQL 的 query。这既避免了您遇到的错误,又避免了 filling up the prepared statement cache.

    await db.query(`START TRANSACTION`);
    await db.execute(`INSERT INTO user VALUES (?, ?, ?, ?, ?, ?)`, [...userDetails]);
    await db.execute(`INSERT INTO account VALUES (?, ?, ?, ?, ?, ?)`, [...accountDetails]);
    await db.query(`COMMIT`);