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();
 }



声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
Land 主题
WordPress 的用户角色和权限
WordPress 增强编辑器功能
Linux apt 命令
数据库中间表应该如何命名
选择排序
阿里云内容安全 API 签名机制
MySQL 字符串截取函数 SUBSTRING_INDEX