查询与参数化

查数据用 query 或 execute。关键是用 ? 占位、把参数单独传进去,mysql2 会替你转义,既防注入又不用手写引号拼接,这是写库代码的基本功。

查询与参数化要点

查询与参数化示例

						async function findOrders(userId) {
						  try {
						    const [rows] = await promisePool.query(
						      'SELECT order_id, amount, status FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 20',
						      [userId]
						    );
						    console.log(rows);
						    return rows;
						  } catch (e) {
						    console.error('查询挂了:', e.message);
						    throw e;
						  }
						}
避坑提醒:别用字符串拼接拼 SQL,哪怕只是个数字 id;一旦混进用户输入,注入漏洞就来了。
查询与参数化 · Node.js 连接 知识卡片
卡片 05 / 09 · Node.js 连接(1080×1440 速查卡片)

Node.js 连接知识点