最近はmysql2というパッケージを利用するのがいいらしい。
特にasync/awaitを利用するときには。
準備
cd
mkdir mysql2-test
cd mysql2-test
npm install mysql2
touch index.js
実装
index.js
const mysql = require("mysql2/promise");
(async () => {
try {
//内容は各自の環境に合わせて変える
const con = await mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "testdb"
});
await con.query("drop table if exists members");
await con.query("create table members(id int, name varchar(32))");
await con.query("insert into members(id,name) values(?,?)", [1, "hoge"]);
await con.query("insert into members(id,name) values(?,?)", [2, "foo"]);
const [rows, fields] = await con.query("select * from members");
for (const row of rows) {
console.log(`id=${row.id}, name=${row.name}`);
}
await con.end();
} catch (e) {
console.log(e);
}
})();
結果
node index.js
id=1, name=hoge
id=2, name=foo
おまけ
敢えてCallback地獄で書く
index.js
const mysql = require("mysql2");
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "testdb"
});
con.query("drop table if exists members", (error, result, fields) => {
if (error) throw error;
con.query("create table members(id int, name varchar(32))", (error, result, fields) => {
if (error) throw error;
con.query("insert into members(id,name) values(?,?)", [1, "hoge"], (error, result, fields) => {
if (error) throw error;
con.query("insert into members(id,name) values(?,?)", [2, "foo"], (error, result, fields) => {
if (error) throw error;
con.end();
});
});
});
});