Node.js MySQL2 如何编写事务

方法一,

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

START TRANSACTION 和 COMMIT 不可以使用 conn.execute,

MySQL limits which statements can be done in prepared statements, start transaction is not allowed. See SQL Syntax Allowed In Prepared Statements and here is a demonstration.

execute is always using and caching prepared statements. This is good if the query is complex (MySQL doesn't have to parse it every time) or takes arguments (for security).

However, if your query is simple and does not take any arguments there's no need to prepare it. Use query which just runs the SQL. This both avoids the error you're getting, and it avoids filling up the prepared statement cache.

方法二,

 let sql = 'select * from tb_user limit 1';
 let values = [];

 const pool = mysql.createPool({
  host: config.database.host,
  port: config.database.port,
  database: config.database.database,
  user: config.database.username,
  password: config.database.password,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
 });

 let conn = null;
 try {
  conn = await pool.getConnection();
  await conn.beginTransaction();

  const [response, meta] = await conn.query(sql);
  await conn.execute(sql, values);
  await conn.execute(sql, values);
  console.log(response);

  await conn.commit();
 } catch (error) {
  if (conn) await conn.rollback();
  throw error;
 } finally {
  if (conn) await conn.release();
 }



声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
随机推荐
Express.js CSRF 安全防护
WordPress 添加自定义接口
JavaScript Date 类型
JavaScript 数组
JavaScript 和 CSS 检测横屏适配
Nginx 使用 Njs 授权访问文件
JavaScript 工作者线程
用 JavaScript 实现数字增加滚动动画