LoginSignup
0
1

More than 3 years have passed since last update.

node環境でのmysql

Last updated at Posted at 2020-09-07

nodejs環境でmysqlを使用する方法

mysqlインスタンスの作成

const mysql = require('mysql')
const connection = mysql.createPool({
     host: 'localhost',
     user: 'root',
     password: 'secret',
     database: 'my_db'
})

データの参照

select文

connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function(error, results, fields){
//error: クエリ実行時にエラーが発生したらエラーオブジェクトを持つ
//results: クエリの実行結果を持つ
//fields: クエリ実行結果のフィールドに関するオブジェクト
})

データの挿入

insert文

connection.query('INSERT INTO `books` SET ?', data, function(error, results, fields){
//error:クエリ実行時にエラーが発生したらエラーオブジェクトを持つ
//results:クエリの実行結果を持つ
//fields:クエリ実行結果のフィールドに関するオブジェクト
})

データの更新

update文

connection.query('UPDATE `books` SET カラム名 = ? WHERE id = ?, ['name', 3], function(error, results, field){
//error:クエリ実行時にエラーが発生したらエラーオブジェクトを持つ
//results:クエリの実行結果を持つ
//fields:クエリ実行結果のフィールドに関するオブジェクト
})

データの削除

delete文

connection.query('DELETE FROM `books` WHERE id = ?', [3], function(error, results, fields){
//error:クエリ実行時にエラーが発生したらエラーオブジェクトを持つ
//results:クエリの実行結果を持つ
//fields:クエリ実行結果のフィールドに関するオブジェクト
})
0
1
1

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
0
1