使用 Node 查詢表中的資料


在本文中,我們將瞭解如何基於不同的表字段和列從資料庫選擇或查詢資料。

在繼續之前,請檢查已執行以下步驟:

  • mkdir mysql-test

  • cd mysql-test

  • npm init -y

  • npm install mysql

以上步驟用於在專案資料夾中安裝 Node - mysql 依賴項。

使用 Node 從表中選擇資料

  • 建立名為 app.js 的新檔案

  • 將以下程式碼段複製並貼上到此檔案中。

  • 現在,執行以下命令以檢查上述程式的輸出。

>> node app.js

示例

// Checking the MySQL dependency – if exists
var mysql = require('mysql');

// Creating connection with the mysql database
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err)
   console.log("Unable to connect to DB ", err);
   con.query("SELECT * FROM students", function (err, result, fields) {
      if (err) throw err;
      console.log(result);
   });
});

輸出

It will return all the records present in the students table:
[ RowDataPacket { id: 1, name: 'John', address: 'Delhi'},
RowDataPacket { id: 2, name: 'Pete', address: 'Mumbai'},
RowDataPacket { id: 3, name: 'Amy', address: 'Hyderabad'},
RowDataPacket { id: 4, name: 'Hannah', address: 'Mumbai'},
RowDataPacket { id: 5, name: 'Mike', address: 'Delhi'}]

使用 Node 查詢表中的資料

以下程式碼段舉例說明了我們如何使用 SQL 查詢來查詢資料並在 Node 中選擇資料。

示例

// Checking the MySQL dependency – if exists
var mysql = require('mysql');

// Creating connection with the mysql database
var con = mysql.createConnection({
   host: "localhost",
   user: "yourusername",
   password: "yourpassword",
   database: "mydb"
});

con.connect(function(err) {
   if (err)
   console.log("Unable to connect to DB ", err);
   con.query("SELECT * FROM student where address='Delhi'; ", function (err, result, fields) {
      if (err) throw err;
      console.log(result);
   });
});

輸出

它將根據我們的篩選條件返回結果:

[ RowDataPacket { id: 1, name: 'John', address: 'Delhi'},
RowDataPacket { id: 5, name: 'Mike', address: 'Delhi'}]

更新於: 28-Apr-2021

162 次瀏覽

開啟您的事業

完成課程以獲得認證

入門
廣告