ไม่ว่าจะเป็น user,password, email และอื่นๆ วันนี้จะมาแนะนำการใช้ NodeJs เชื่อมต่อกับ database วิธีการ connect การตั้งค่า และการ query ข้อมูล กับ NodeJS
ฐานข้อมูลที่จะใช้เป็นตัว MySQL โดยสามารถ download ได้จาก โปรแกรม XAMPP
เมื่อทำการติดตั้งเสร็จแล้วให้ทำการเปิดโปรแกรมมีหน้าต่างของ control panel เปิดขึ้นมา
จะมีชื่อของ module ที่จะใช้ run mysql คือ apache และ mysql ให้ทำการ start ทั้ง 2 ตัว
หลังจากนั้นให้ทำการสร้างฐานข้อมูลขึ้น ตั้งชื่อตามที่ถนัด และสร้าง table ที่ใช้สำหรับเก็บข้อมูล
ใน table จะประกอบไปด้วย column 3 column
1. product_id type int
2. product_name type varchar
3. product_price type varchar หลังจากสร้าง database และ table เสร็จแล้วให้ทำการสร้าง folder ที่จะใช้กับ nodejs และใช้ vscode ในการสร้างไฟล์ project ของ nodejs
ขั้นตอนแรกให้ทำการติดตั้ง
1.ติดตั้ง npm init ไฟล์ที่ได้จะเป็น package.json ที่จะใช้บอก version ของงานเรา
2. ติดตั้ง express.js, npm install express
3. ติดตั้ง mysql, npm install mysql
จะชัดเกตุว่าในไฟล์ package.json จะมี fied ที่ชื่อว่า dependencies ซึ่งที่ที่ใช้ในการเก็บ package ทั้งหมดของ NPM
หลังจากที่ติดตั้งทุกอย่างเรียบร้อยแล้ว ให้ทำการสร้างไฟล์ index.js ขึ้นมาแล้วเขียนโค้ดเพื่อใช้ในการทดสอบการเชื่อมต่อกับ database
โค้ด: เลือกทั้งหมด
var mysql = require('mysql');
// create connection
var con = mysql.createConnection({
host:"localhost",
user:"root",
password:"",
database:"employee_database"
});
//Connect Db
con.connect(function(err){
if (err) throw err;
console.log("Connected!");
});
โค้ด: เลือกทั้งหมด
con.connect(function(err){
if (err) throw err;
console.log("Connected!");
sql = "insert into product (product_name,product_price) values('Mouse',3000)";
con.query(sql, function (err, result){
if (err) throw err;
console.log("Insert Complete");
});
});
การทำ MVC Framework นั้นจะต่อมีการเชื่อมต่อกับ ฐานข้อมูลเชื่อมเพื่อใช้ในการเก็บข้อมูลต่างๆในตัว project นั้น ซึ่ง NodeJS เองก็เช่นกัน จะต้องมีการใช้ในการเชื่อมต่อกับ database โดยในเบื่องต้นได้แนะนำการเชื่อมต่อ NodeJs กับ MySQL และการ query ข้อมูลลง database และ table
แล้วซึ่งมีประโยชน์อย่างมากในการทำงานของฝั่ง backend
https://www.mikkipastel.com/express-js-crash-course/
https://www.sitepoint.com/using-node-mysql-javascript-client/
https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm