新增與更新
最後更新
本頁說明 insert()、update() 與 increase() 的行為,以及 MySQL 函式白名單在哪些方法生效。
insert()
const id = await MySQLPool
.table("users")
.insert({ name: "John Doe", email: "john@example.com" });
// INSERT INTO `users` (`name`, `email`) VALUES (?, ?)
| 項目 | 行為 |
|---|---|
| 連線池 | 寫入池 |
| 回傳 | insertId;為 0(例如沒有 AUTO_INCREMENT 欄位)時回傳 null |
| 值 | 全部以佔位符綁定 |
update()
const result = await MySQLPool
.table("users")
.where("id", 1)
.update({ name: "Jane Doe", updated_at: "NOW()" });
// UPDATE `users` SET `name` = ?, `updated_at` = NOW() WHERE `id` = ?
console.log(result.affectedRows);
| 項目 | 行為 |
|---|---|
| 連線池 | 寫入池 |
| 回傳 | mysql2 的 ResultSetHeader(affectedRows、changedRows 等) |
| 白名單函式 | 值(不分大小寫)完全等於白名單項目時原樣寫入 SQL |
increase()
increase(column, n) 在 update() 的 SET 子句加入 column = column + n:
await MySQLPool
.table("users")
.where("id", 1)
.increase("login_count")
.increase("score", 5)
.update({ last_login: "NOW()" });
// UPDATE `users` SET login_count = login_count + 1, score = score + 5, `last_login` = NOW() WHERE `id` = ?
| 規則 | 說明 |
|---|---|
| 預設增量 | 1 |
| 遞減 | 傳負數,例如 increase("stock", -1) |
MySQL 函式白名單
update() 與 upsert() 的值等於下列任一項時原樣寫入 SQL(src/MySQLPool.ts:31-36):
NOW()、CURRENT_TIMESTAMP、UUID()、RAND()、CURDATE()、CURTIME()、UNIX_TIMESTAMP()、UTC_TIMESTAMP()、SYSDATE()、LOCALTIME()、LOCALTIMESTAMP()、PI()、DATABASE()、USER()、VERSION()