0615 express서버와 mysql 커넥션
2021. 6. 15. 12:22ㆍNode.js
npm init -y
npm i express
npm i mysql2
const port = 3000;
const mysql = require('mysql2');
const connection = mysql.createConnection({
host:'localhost',
user:'root',
database:'nodejs',
password:'mysql 유저 패스워드 삽입',
});
app.get('/',(req,res)=>{
res.end('hello world');
});
app.get('/dbconnect',(req,res)=>{
console.log(connection);
res.end('connection test');
});
app.listen(port,()=>{
console.log(`server is running at ${port}`);
});
//app.js
const express = require('express');
const app = express();
const port = 3000;
const mysql = require('mysql2');
const connection = mysql.createConnection({
host:'localhost',
user:'root',
database:'nodejs',
password:'qwerpoiu!@#',
});
app.get('/',(req,res)=>{
res.end('hello world');
});
app.get('/:id',(req,res)=>{
const id = req.params.id;
const query =`SELECT*FROM products WHERE id=${id}`;
console.log(query);
//DB 서버로 부터 전송 받는 부분
connection.execute(query,(err,results,fields)=>{
if(err) throw err;
const result = {
status: 200,
results,
};
//클라이언트에게 응답하는 부분
const json = JSON.stringify(result);
res.send(json);
});
});
app.listen(port,()=>{
console.log(`server is running at ${port}`);
});
const express = require('express');
const app = express();
const port = 3000;
const mysql = require('mysql2');
const connection = mysql.createConnection({
host:'localhost',
user:'root',
database:'nodejs',
password:'mysql 유저 비번',
});
app.get('/:id',(req,res)=>{
const id = req.params.id;
const query =`SELECT * FROM products WHERE id=${id}`;
console.log(query);
//DB 서버로 부터 전송 받는 부분
connection.execute(query,(err,results,fields)=>{
if(err) throw err;
const result = {
status: 200,
results,
};
//클라이언트에게 응답하는 부분
const json = JSON.stringify(result);
res.send(json);
});
});
app.post('/products',(req,res)=>{
let sql = "INSERT INTO products (name, category, price) VALUES ('닌텐도 스위치 본체 모여봐요 dddddddd','3510','427000')";
connection.execute(sql,(err,results,fields)=>{
let result ={
status: 200,
}
if(err) result.status=500;
res.send(result);
});
});
app.delete('/products',(req,res)=>{
let sql = "DELETE FROM products WHERE id=10 ";
connection.execute(sql,(err,results,fields)=>{
let result = {
status: 200,
}
if(err) result.status=500;
res.send(result);
});
});
app.put('/products',(req,res)=>{
let sql = "UPDATE products SET name='닌텐도 스위치 젤다의 전설 브레스 오브 더 와일드' WHERE id=7";
connection.execute(sql,(err,results,fields)=>{
let result = {
status: 200,
}
if(err) result.status=500;
res.send(result);
});
})
app.listen(port,()=>{
console.log(`server is running at ${port}`);
});
'Node.js' 카테고리의 다른 글
0617 GPGS (0) | 2021.06.17 |
---|---|
0616 Sequelize (0) | 2021.06.16 |
0611 express 서버 이어서 (0) | 2021.06.11 |
0610 서버 데이터 전송 방법에 따라 구현하기 (0) | 2021.06.10 |
0609 express 서버 열기 (0) | 2021.06.09 |