Sunday, November 19, 2017

Belajar Node.js Part 15 - Select From MySQL




Untuk menyeleksi data dari sebuah tabel di MySQL, gunakan pernyataan "SELECT".

Contohnya, jika kita menyeleksi semua records dari tabel "pelanggans", dan menampilkan result object-nya:

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: "localhost",
  user: "nama_anda",
  password: "password_anda",
  database: "dbsaya"
});

connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT * FROM pelanggans", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

Simpan kode tersebut dengan nama "mysql_7.js", kemudian jalankan perintah ini:
node mysql_7.js

Hasilnya akan seperti ini:

[
  { id: 1, name: 'Jack1', address: 'Jalan Mawar 715'},
  { id: 2, name: 'Jack2', address: 'Jalan Mawar 44'},
  { id: 3, name: 'Jack3', address: 'Jalan Mawar 6525'},
  { id: 4, name: 'Jack4', address: 'Jalan Mawar 216'},
  { id: 5, name: 'Jack5', address: 'Jalan Mawar 3454'},
  { id: 6, name: 'Jack6', address: 'Jalan Mawar 21'},
  { id: 7, name: 'Jack7', address: 'Jalan Mawar 12'},
  { id: 8, name: 'Jack8', address: 'Jalan Mawar 3'},
  { id: 9, name: 'Jack9', address: 'Jalan Mawar 6'},
  { id: 10, name: 'Jack10', address: 'Jalan Mawar 27'},
  { id: 11, name: 'Jack11', address: 'Jalan Mawar 389'},
  { id: 12, name: 'Jack12', address: 'Jalan Mawar 95'},
  { id: 13, name: 'Jack13', address: 'Jalan Mawar 98'},
  { id: 14, name: 'Jack14', address: 'Jalan Mawar 16'}
]

Menyeleksi Kolom

Untuk menyeleksi hanya beberapa dari kolom dalam sebuah tabel, gunakan pernyataan "SELECT" diikuti dengan nama kolom.

[MY_ADS/]

Contohnya, jika kita akan menyeleksi nama dan alamat dari tabel "pelanggans" dan menampilkan result object:

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: "localhost",
  user: "nama_anda",
  password: "password_anda",
  database: "dbsaya"
});

connection.connect(function(err) {
  if (err) throw err;
  connection.query("SELECT name, address FROM pelanggans", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

Simpan kode tersebut dengan nama "mysql_8.js", kemudian jalankan perintah ini:
node mysql_8.js
Hasilnya akan seperti ini:

[
  { name: 'Jack1', address: 'Jalan Mawar 715'},
  { name: 'Jack2', address: 'Jalan Mawar 44'},
  { name: 'Jack3', address: 'Jalan Mawar 6525'},
  { name: 'Jack4', address: 'Jalan Mawar 216'},
  { name: 'Jack5', address: 'Jalan Mawar 3454'},
  { name: 'Jack6', address: 'Jalan Mawar 21'},
  { name: 'Jack7', address: 'Jalan Mawar 12'},
  { name: 'Jack8', address: 'Jalan Mawar 3'},
  { name: 'Jack9', address: 'Jalan Mawar 6'},
  { name: 'Jack10', address: 'Jalan Mawar 27'},
  { name: 'Jack11', address: 'Jalan Mawar 389'},
  { name: 'Jack12', address: 'Jalan Mawar 95'},
  { name: 'Jack13', address: 'Jalan Mawar 98'},
  { name: 'Jack14', address: 'Jalan Mawar 16'}
]

Sumber:
https://www.w3schoools.com