조금 검색해보니까 node.js는 mongoDB랑 잘 맞다고 하던데
나는 관계형 데이터베이스가 필요하다고 생각했고, sql을 배우고 있어서 mysql를 연동시키기로 했다.
//index.js
const express = require('express') //express 모듈 가져옴
const app = express() //함수를 이용해 새로운 app을 만듦
const port = 3000 //3000번 포트를 백서버로 둠
const mysql = require('mysql')
const dbconfig = require('./config/database.js')
const connection = mysql.createConnection(dbconfig)
connection.connect(function(err) {
if (err) throw err;
console.log('db connected')
});
app.get('/', (req, res) => {
res.send('Hello World!') //'/'디렉토리에 오면 Hello World 출력
})
app.get('/users', (req, res) => {
connection.query('select * from Users', (error, rows) => {
if (error) throw error;
console.log('User info is: ', rows)
res.send(rows)
})
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}!`)
}) //3000번 포트에서 실행
// connection.end()
먼저
npm install express mysql
로 express와 mysql을 설치하고
const mysql = require('mysql')
const dbconfig = require('./config/database.js')
const connection = mysql.createConnection(dbconfig)
로 mysql을 불러온다
mysql.createConnection 안에는 host명, user명, password, database명이 들어가야 하는데
github에 올릴 것이기에 보안상 index.js에 적지 않고 config/databases.js에 따로 이 내용들을 빼주었다
module.exports = {
host : 'localhost',
user : '<user_name>',
password : '<password>',
database : '<database_name>'
}
host는 보통 localhost일 것이라고 생각한다
사용할 DB에 맞는 값들을 넣어주면 된다
그러면 http://localhost:3000/user에 들어가면 User 테이블에 있는 정보들이 불러와진다
여기서는 User 테이블과 그 안에 값을 넣어놓지 않았기에 오류 혹은 아무 것도 뜨지 않는게 맞다
아래 블로그에 DB를 생성하고 값을 넣는 내용까지 포함되어있다
참고 블로그
https://poiemaweb.com/nodejs-mysql
MySQL 연동 | PoiemaWeb
Node.js(express)와 MySQL 연동
poiemaweb.com
'웹 > MYSQL' 카테고리의 다른 글
csv 파일을 mysql에 저장하는 방법/csv 파일 db에 저장 (0) | 2023.07.07 |
---|---|
[mysql] DB hijacking, README TO RECOVER A.RECOVER YOUR DATA (0) | 2023.05.29 |
[mysql] Unit file mysqld.service does not exist. (0) | 2023.05.27 |
[mysql / 에러] Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts (0) | 2023.05.24 |
댓글