如何將 MySQL2 與 Deno 搭配使用
MySQL 是 2022 年 Stack Overflow 開發人員調查 中最受歡迎的資料庫,其使用者包括 Facebook、Twitter、YouTube 和 Netflix。
您可以使用 mysql2
節點套件並透過 npm:mysql2
匯入,以 Deno 處理和查詢 MySQL 資料庫。這讓我們可以使用其 Promise 封裝,並利用頂層 await。
import mysql from "npm:mysql2@^2.3.3/promise";
連線至 MySQL
我們可以使用 createConnection()
方法連線至我們的 MySQL 伺服器。您需要主機(如果您正在測試,則為 localhost
,或在生產環境中更有可能是雲端資料庫端點)以及使用者和密碼
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
});
您也可以在建立連線時選擇性地指定資料庫。在此處,我們將使用 mysql2
即時建立資料庫。
建立並填入資料庫
現在您已執行連線,您可以使用 connection.query()
搭配 SQL 指令來建立資料庫和表格,以及插入初始資料。
首先,我們想要產生並選取要使用的資料庫
await connection.query("CREATE DATABASE denos");
await connection.query("use denos");
接著,我們想要建立表格
await connection.query(
"CREATE TABLE `dinosaurs` ( `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` varchar(255) NOT NULL, `description` varchar(255) )",
);
建立表格後,我們可以填入資料
await connection.query(
"INSERT INTO `dinosaurs` (id, name, description) VALUES (1, 'Aardonyx', 'An early stage in the evolution of sauropods.'), (2, 'Abelisaurus', 'Abels lizard has been reconstructed from a single skull.'), (3, 'Deno', 'The fastest dinosaur that ever lived.')",
);
現在我們已準備好所有資料,可以開始查詢。
查詢 MySQL
我們可以使用相同的 connection.query() 方法來撰寫我們的查詢。首先我們嘗試並取得我們 dinosaurs
表格中的所有資料
const results = await connection.query("SELECT * FROM `dinosaurs`");
console.log(results);
這個查詢的結果是我們資料庫中的所有資料
[
[
{
id: 1,
name: "Aardonyx",
description: "An early stage in the evolution of sauropods."
},
{
id: 2,
name: "Abelisaurus",
description: `Abel's lizard" has been reconstructed from a single skull.`
},
{ id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." }
],
如果我們只想從資料庫中取得單一元素,我們可以變更我們的查詢
const [results, fields] = await connection.query(
"SELECT * FROM `dinosaurs` WHERE `name` = 'Deno'",
);
console.log(results);
這會給我們單一列的結果
[{ id: 3, name: "Deno", description: "The fastest dinosaur that ever lived." }];
最後,我們可以關閉連線
await connection.end();
有關 mysql2
的更多資訊,請查看他們的說明文件 在此。