LoginSignup
0
2

More than 3 years have passed since last update.

【Node.js mysql】mysql接続 データを取り出す

Posted at

【ゴール】

mysql接続 データを取り出す

【開発環境】

■ Mac OS catalina
■ Homebrew 2.4.9
■ mysql Ver 8.0.21

【実装】

appを作成

homebrewのインストールが事前に必要です
mysqlのインストールが事前に必要です
*mysqlのコマンドも合わせて覚えれます

mac.terminal
// ディレクトリ作成

$ mkdir js
$ cd js
$ npm init -y
$ npm install express
$ npm install ejs
$ npm isntall mysql
$ touch server.js
$ touch app.ejs

// mysql でDATABASEを作成

$ mysql -u root -p
$ mysql> CREATE DATABASE JS;
$ use JS;
$ CREATE TABLE User (id int auto_incremet, name char(10));
$ INSERT INTO User value (1, tarou);

コーディング


■ npmのmysqlを読み込み。
■「createCOnnection」で({})内の任意のDBに接続


■ cosnt sql = データベースへの命令を定数へ
■「query」メソッドで、DBへ命令
■「if(err) throw err;」はエラーがあっても挙動させる
■「err, result」にDBからのデータが格納されています

server.js
const express = require('express');
const app = express();

// ① 〜
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'あなたのsqlのパスワード',
  database: 'JS'
});
// ここまで

function views (){
  app.set('views', 'views'),
  app.set('view enigine', 'ejs');
}

app.get('/', (req, res) => {
 // ② 〜
  const sql = 'select * from User id = 1';
  connection.query(sql, (err, result) => {
    if(err) throw err;
    console.log(result);
    views();
    res.render('app', {user: result} );
  })
 // ここまで②
})

app.listen(3000, (req, res) => {
  console.log('success');
})
app.ejs
<%= user.id %>
<%= user.name %>

確認

*localhost 3000接続

mac.terminal
$ node app.js
success

以上

【合わせて読みたい】

■ 【HOMEBREW】 Mac OSのパッケージマネージャーについて node.jsやってたら学んだ事
https://qiita.com/tanaka-yu3/items/65dac47443cc08914a86

■【node.js】 node.jsインストール 芋っていたけど、簡単だった件...
JavaScript
https://qiita.com/tanaka-yu3/items/739db5ffed24a8d9ae4b

■DBonline
https://www.dbonline.jp/

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