Ⅱ. やり方
1. 必要なパッケージをインストールする
npm install mysql2
2. サンプルプログラムを書く
const mysql = require('mysql2');
const util = require('util');
(async () => {
const pool = mysql.createPool({
connectionLimit: 10,
host: '127.0.0.1',
user: 'user',
password: 'my_password',
database: 'my_database'
})
pool.query = util.promisify(pool.query)
let results = await pool.query('select * from accounts')
console.log(results)
let data = { id: 2, name: 'name002' }
await pool.query('insert into accounts set ?', data)
results = await pool.query('select * from accounts')
console.log(results)
pool.end()
})()
実行結果
[ RowDataPacket { id: 1, name: 'name001' } ]
[ RowDataPacket { id: 1, name: 'name001' },
RowDataPacket { id: 2, name: 'name002' } ]