10월 17일 (일) MySQL (Batch Mode, dotenv, mysql)

Southbig·2021년 10월 17일
0

MySQL

Batch Mode

  1. mysql에 접속해 cmarket 데이터베이스를 생성

mysql에 접속한 뒤 입력
CREATE DATABASE <데이터베이스 이름>;

  1. 미리 구성되어 있는 스키마를 기반으로 MySQL에 데이터베이스의 테이블을 생성
    다음 명령어로 데이터베이스에 테이블을 생성

CLI(터미널) 환경에서 레포지토리에 진입하여 커맨드를 입력
mysql -u root -p < <작성된 스키마파일.sql> -D<데이터베이스이름>

  1. 위에서 생성한 테이블에 기반이 되는 데이터를 다음 명령어로 저장

CLI(터미널) 환경에서 레포지토리에 진입하여 커맨드를 입력
mysql -u root -p < <데이터파일.sql> -D<스키마된 데이터베이스>

  • 파일 스키마파일.sql 은 관계형 데이터베이스의 기초 뼈대의 역할을 한다
    스키마파일.sql을 활용하여 내부 테이블을 생성하고, 커맨드 창에 명령어를 하나하나 입력하는 방법과 다르게, 필요한 명령을 정리한 파일을 작성한 다음 배치모드로 실행 중인 MySQL 서버에 한 번에 적용

  • 파일 데이터파일.sql 은 생성한 데이터베이스 테이블에 준비된 데이터를 미리 저장한다
    데이터베이스의 스키마의 구성과 다르면, 데이터가 저장되지 않는다

  • PATH/TO/YOUR/스키마파일.sql 은 터미널의 현재 위치에서 스키마파일.sql의 위치까지 경로를 지정해야 한다는 의미

  • 잘못된 SQL을 작성하여 잘못된 데이터베이스 및 테이블이 생성된 경우, 잘못 생성된 데이터베이스를 삭제하고 다시 생성할 수 있다
    이 작업은 잘못 생성된 데이터베이스의 모든 테이블과 데이터를 제거한다
    SQL 명령어로
    DROP DATABASE IF EXISTS [다시 생성하려는 데이터베이스]
    CREATE DATABASE [다시 생성하려는 데이터베이스] 를 입력하면 원하는 결과를 얻을 수 있다
    이 SQL 명령어가 실행되면 기존 데이터베이스를 제거하고, 작성된 SQL 명령어에 따라 데이터베이스를 다시 생성한다

github MySQL Batch Mode

npm

dotenv

Dotenv는 .env 파일에서 process.env로 환경 변수를 로드하는 zero-dependency module이다

install

with npm
npm install dotenv
or with Yarn
yarn add dotenv

usage

  1. As early as possible in your application, require and configure dotenv

require('dotenv').config()

const dotenv = require('dotenv');
dotenv.config();
  1. Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

  1. process.env now has the keys and values you defined in your .env file
const db = require('db')
db.connect({
  host: process.env.DB_HOST
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Config

config will read your .env file, parse the contents, assign it to process.env, and return an Object with a parsed key containing the loaded content or an error key if it failed

const result = dotenv.config()

if (result.error) {
  throw result.error
}

console.log(result.parsed)

github npm dotenv

mysql

Install

$ npm install mysql

Introduction

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});
 
connection.connect();
 
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});
 
connection.end();
  • Every method you invoke on a connection is queued and executed in sequence.
  • Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Establishing connections

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'example.org',
  user     : 'bob',
  password : 'secret'
});
 
connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }
 
  console.log('connected as id ' + connection.threadId);
});

쿼리를 사용해 암묵적으로 연결할 수 있다

var mysql      = require('mysql');
var connection = mysql.createConnection(...);
 
connection.query('SELECT 1', function (error, results, fields) {
  if (error) throw error;
  // connected!
});
profile
즐겁게 살자

0개의 댓글