Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ลบ Record ใน MySQL ด้วย Node.js (DELETE FROM)

ลบ Records จาก MySQL ด้วย Node.js ใช้คำสั่ง DELETE FROM

2 วิธี

  • Static Deletion: Filter Value คงที่
  • Dynamic Deletion: รับ Input ก่อนลบ

Prerequisites

mkdir mysql-test
cd mysql-test
npm init -y
npm install mysql

ตัวอย่างที่ 1: Static Deletion

var mysql = require('mysql');
var con = mysql.createConnection({
  host: "localhost", user: "yourusername", 
  password: "yourpassword", database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  var sql = "DELETE FROM student WHERE address = 'Delhi';";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Record deleted = ", result.affectedRows);
    console.log(result);
  });
});

Output

Record deleted = 1
OkPacket { affectedRows: 1, serverStatus: 34, warningCount: 0, ... }

ตัวอย่างที่ 2: Dynamic Deletion (Parameterized Query)

con.connect(function(err) {
  if (err) throw err;
  let sql = `DELETE FROM student WHERE address = ?`;
  con.query(sql, 'Delhi', (err, result, fields) => {
    if (err) throw err;
    console.log("Record deleted = ", result.affectedRows);
    console.log(result);
  });
});

Output

OkPacket { affectedRows: 3, serverStatus: 34, warningCount: 0, ... }

ข้อสังเกต

  • ใช้ Parameterized Query (?) ป้องกัน SQL Injection
  • affectedRows แสดงจำนวนแถวที่ลบ
  • Dynamic Deletion ปลอดภัยและยืดหยุ่นกว่า