7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

node.js + mysql (2021)

Last updated at Posted at 2021-08-17

最近は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();
            });
        });
    });
});
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?