728x90

자바 프로젝트를 데이터베이스에 연결하기 위해서는 다음과 같은 단계를 거친다. 

1. JDBC 드라이버 로드  (JDBC java Database Connectivity 자바와 디비 연결을 돕는 api들을 제공해준다)

2. 데이터베이스와 연결

3. SQL문 실행

4. 데이터베이스와 연결 끊음

 

나는 1번부터 막혔다! (이클립스에서 인텔리제이로 넘어오면서 책에 예시가 없어서 다 찾아봐야했다)

maven이나 gradle을 써서 사용하는 드라이버 설정을 해줘야하나 싶었지만 역시나 해결이 안됨.

 

마리아 디비 드라이버 다운 

https://mariadb.com/downloads/connectors/connectors-data-access/java8-connector

+ java 눌러서 다운받은 드라이버넣어줬는데도

Class.forName("org.mariadb.jdbc.Driver");

부터 통과가 안됐다! 드라이버를 못가져오는거같은데...

 

 

해결방법

 

이 블로그를 보고 도움 받았다!

"WEB-INF/lib 안에 mariadb-java-client-2.6.2.jar을 빌드 해주야 해결이 된다" !

https://jung-story.tistory.com/108

 

Avaliable Elements 안에 TEST 안에 있는 

maraidb 파일을 클릭해서 왼쪽 lib 안에 집어넣는다.

 

드라이버 연결 DBManager

 

package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBManager {
    public static Connection getConnection(){


        Connection con = null;

        String server = "서버주소(나는 localhost)";
        String database = "데이터베이스 이름";
        String user_name = "유저네임";
        String password = "비밀번호";

        try {
            Class.forName("org.mariadb.jdbc.Driver");
            System.out.println("드라이브로드 성공");

        } catch (ClassNotFoundException e) {
            System.err.println(" 드라이버 로딩 오류 : " + e.getMessage());
            e.printStackTrace();
        }

        try {
            con = DriverManager.getConnection("jdbc:mariadb://" +
                    server + "/" +
                    database +
                    "?useSSL=false", user_name, password); // SSL 실행 확인
            System.out.println("연결 성공");
        } catch(Exception e) {
            System.err.println("에러 내용 :" + e.getMessage());
            e.printStackTrace();
        }

        System.out.println("con리턴" +con);
        return con;



    }
    //select 수행한 후 리소스 해제를 위한 메소드
    public static void close(Connection conn, Statement stmt, ResultSet rs){
        try{
            rs.close();
            stmt.close();
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //insert, update, delete 작업을 수행한 후 리소스 해제를 위한 메소드
    public static void close(Connection conn, Statement stmt){
        try{
            stmt.close();
            conn.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

ProductDAO

에서 getInstance를 통해 연결!

package com.saeyan.dao;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import util.DBManager;

import com.saeyan.dto.ProductVO;

public class ProductDAO {
    private ProductDAO(){

    }
    private static ProductDAO instance = new ProductDAO();
    public static ProductDAO getInstance(){
        return instance;
    }

    //c Read u d
    public  List<ProductVO> selectAllProducts(){
        //최근 등록한 상품 먼저 출력하기
        String sql= "select * from product order by code desc";
        List<ProductVO> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try{
            conn = DBManager.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();


            while (rs.next()){
                ProductVO pVo = new ProductVO();
                pVo.setCode(rs.getInt("code"));
                pVo.setName(rs.getString("name"));
                pVo.setPrice(rs.getInt("price"));
                pVo.setPictureUrl(rs.getString("pictureurl"));
                pVo.setDescription(rs.getString("description"));

                list.add(pVo); //앗 얘를 빼먹었었네!
            }


        } catch(Exception e){
            System.out.println("값 못가져옴:"+e.getMessage());


        } finally {
            DBManager.close(conn, pstmt, rs);
        }
        return list;
    }

}
728x90
728x90

prisma init

 

 

schema.prisma 파일안에 

datasource db {
    provider = "mysql"
    url      = "mysql://유저:비번@localhost:3306/markhouse__"
}

//Prisma Generate는 데이터 모델을 사용하여 Prisma Client를 생성하는 도구입니다. 
//Prisma Client를 사용하면 데이터베이스에 대한 CRUD 작업을 쉽게 수행할 수npx prisma migrate reset 있습니다.

generator client {
    provider = "prisma-client-js"
}

model User {
    id    Int     @id @default(autoincrement())
    email String  @unique
    name  String?
    posts Post[]
}

model Post {
    id       Int    @id @default(autoincrement())
    title    String
    author   User   @relation(fields: [authorId], references: [id])
    authorId Int
}

 

❯ npx prisma db push
Prisma schema loaded from prisma/schema.prisma
Datasource "db": MySQL database "markhouse__" at "localhost:3306"

MySQL database markhouse__ created at localhost:3306

🚀  Your database is now in sync with your Prisma schema. Done in 136ms

✔ Generated Prisma Client (4.10.1 | library) to ./node_modules/@prisma/client in 44ms

 

| markhouse__생김

 

 

 

 

+

만약 show tables를 실행했을 때 _prisma_migrations 테이블만 보인다면, 아마도 Prisma Migrate를 통해 생성한 마이그레이션 파일로 데이터베이스 스키마를 생성하지 않은 것으로 추정됩니다.

Prisma Migrate를 사용하여 데이터베이스 스키마를 생성하려면 다음과 같은 단계를 따라야 합니다.

  1. prisma init 명령어를 사용하여 Prisma 프로젝트를 초기화합니다.
  2. schema.prisma 파일을 생성하고, 데이터베이스 스키마를 정의합니다.
  3. prisma migrate save 명령어를 사용하여 마이그레이션 파일을 생성합니다.
  4. prisma migrate up 명령어를 사용하여 마이그레이션을 적용하여 데이터베이스 스키마를 생성합니다.

위 단계를 수행하고 나면 show tables 명령어를 실행하여 데이터베이스 내 모든 테이블을 볼 수 있습니다. 만약 테이블이 여전히 보이지 않는다면, DBeaver에서 해당 데이터베이스에 대한 연결을 확인해야 합니다. 데이터베이스 연결이 올바른지 확인하고, 다시 시도해 보시기 바랍니다.

 

 

권한 문제가 생긴다면

 

모든 사용자 조회하는 법 

SELECT user, host FROM mysql.user;

 

사용자 조회해보고

비밀번호 확인해볼 것(모른다면 재설정하기)

ALTER USER '사용자명'@'호스트명' IDENTIFIED BY '새로운 비밀번호';

또는

ALTER USER '사용자명'@'호스트명' IDENTIFIED WITH mysql_native_password BY 'new_password';

 

권한도 확인해볼 것

권한 체크 

SHOW GRANTS FOR 'database_user'@'localhost';

권한 주기

GRANT CREATE, DROP ON *.* TO 'database_user'@'localhost';

 

 

root 모든 걸 볼수 있는거 

다른 권한에서 만든 것도 볼 수 있음 

 

다른 유저로 안들어가졌던 이유는 그저 비번 틀려서 접근 안되었던 거였음. 

 

dbeaver는 그냥 mysql에서 만든 데이터 깔끔하게 보여주는 툴임. 

localhost, 유저, 비번 잘입력하면 연결은 되어서 생성됨

 

추가로 테이블 생성했을 때 mysql터미널에서는 생긴게 보이는데 dbeaver에 바로 반영안되는 이유가 뭐지?

아 dbeaver refresh 버튼 눌러서 새로고침하니까 있다 얏호~!~!~!~

 

 

 

+

 

root는 MySQL에서 가장 높은 권한을 가진 사용자입니다. root 사용자는 모든 데이터베이스와 모든 객체에 대한 모든 권한을 가지고 있습니다. 즉, root 사용자는 MySQL 서버에서 모든 작업을 수행할 수 있습니다.

MySQL에서 root 사용자는 기본적으로 "localhost" 호스트에서만 로그인할 수 있습니다. 이는 보안상의 이유로 설정되어 있습니다. 따라서, 원격 호스트에서 root 계정으로 로그인하려면 특별한 설정이 필요합니다.

그러나, root 계정은 매우 강력하며 위험하기 때문에 일반적으로 MySQL 서버에는 다른 사용자 계정을 만들어 사용합니다. 이렇게 하면 보안상의 문제를 최소화할 수 있습니다.

 

+

 

sudo는 "Superuser Do"의 준말로, 리눅스나 유닉스 시스템에서 일반 사용자가 시스템 관리자(root)의 권한을 일시적으로 얻을 수 있는 명령어입니다.

리눅스나 유닉스 시스템에서 root 계정은 시스템 전체를 관리할 수 있는 권한을 가지고 있으므로, root 권한을 가진 사용자로 로그인하면 시스템 보안에 큰 위험이 따릅니다. 따라서, 보안상의 이유로 일반 사용자가 root 권한을 가지지 못하도록 설정되어 있습니다.

이때, 일반 사용자가 시스템 관리 작업을 수행해야 할 경우, sudo 명령어를 사용하여 일시적으로 root 권한을 얻을 수 있습니다. 이때, 사용자는 자신이 수행하려는 작업을 sudo 명령어 뒤에 입력하면 됩니다.

예를 들어, 일반 사용자가 시스템 업데이트를 수행하려면 다음과 같이 sudo 명령어를 사용할 수 있습니다.

 

+

mysql_native_password는 MySQL에서 기본으로 제공하는 인증 플러그인 중 하나입니다.

이 플러그인은 기존의 비밀번호 인증 방식과 호환되도록 설계되어 있어, 기존에 비밀번호로 인증했던 사용자들도 계속해서 이 플러그인을 사용하여 인증할 수 있습니다.

auth_socket 플러그인과 달리, mysql_native_password 플러그인을 사용하는 경우에는 비밀번호가 필요합니다. 따라서, 해당 사용자의 비밀번호를 잊어버린 경우에는 비밀번호를 재설정해주어야 합니다.

만약 mysql_native_password 플러그인 대신 caching_sha2_password 플러그인을 사용하는 경우에는, 새로운 비밀번호를 설정할 때 IDENTIFIED WITH mysql_native_password 구문을 생략해야 합니다.

 

728x90
728x90

https://stepby-yun.tistory.com/192?category=554522 

 

mysql while 여러시도..

https://stepby-yun.tistory.com/191 mysql procedure 프로시저 생성 및 실행 (구본문자 DELIMITER ) while문 해보려는데.. 나와같은 의문을 가지신 분 프로시저 꼭 만들어서 써야돼? https://stackoverflow.com/q..

stepby-yun.tistory.com

프리비어슬리~

 

새로 생긴 행이랑 이전 행 시간을 빼서 1분 이상일때마다

값을 넣어줄까? 했는데 무한insert되고 난리남

 

(이 글의 결론)

1분이 흐를때마다 ->이자증액값을 넣어준다

에서

값넣는다. 1분마다시간증가, 이자증액, 

이렇게

insert할때 한꺼번에 넣는 걸로 식만듦..(저번에 한달씩 증가랑 똑같이 함.)

------

 

 

 

기준 잡기의 중요성..

한 시간씩 증가하고

넣고 먼저 해보자

최대증가한 시간

몇번째 행의 시간이 얼만지 생각! 

 


 

use test;
truncate sequence;


set @setTime = (select subtime(now(),'00:02:00'));

insert into sequence (name,deposit_date,deposit_amount,interest_amount) values ('이소윤',@setTime,'10000000','0');

drop procedure if exists pro;
delimiter //
create procedure pro()
begin
while (select id from sequence order by id desc limit 1) < 10 do


INSERT INTO sequence (name,deposit_date,deposit_amount,interest_amount) 
select 
(select name from sequence order by id desc limit 1),
date_add((select deposit_date from sequence where  deposit_date order by id desc limit 1),INTERVAL 1 hour),
((select deposit_amount from sequence where  deposit_amount order by id desc limit 1) + (select interest_amount from sequence where  interest_amount order by id desc limit 1)),
(select deposit_amount from sequence where id='1')* 0.04 /12;

end while;
end //
delimiter ;

call pro();

select * from sequence;
 


아 다음행에 insert 추가 되는게

마지막 id가 9이니까

 

10까지 뜨는거구나~!!

 

그래도 deposit_amount의 마지막행 10000000을 구해서 이자액 33333을 구했으면 

 

2번째 행에 deposit_amount도 들어갈 수 있는거 아닌가 왜 

 

null값이지? 

 

 

+

 

지금은 한번에 들어가는거니까 

날짜를 추가하고 추가될때마다 이자액이 찍히게 하면 되려나...

 

 

update써서 해보자

 

update 안되는이유 여기서 세팅 설정바꿔줘야함

https://lightblog.tistory.com/193

 

[MYSQL] 에러 번호 1175 Safe Update 해결방법

MySQL에서 쿼리를 실행하다보면 다음과 같은 에러를 마주할 때가 있다. Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable..

lightblog.tistory.com

오마갓 숫자를 ''

여기 넣어서 문자열로 만들어서 쓰고있었네

 

 

 

 

하지만 잘 안됨

use test;
truncate sequence;
set @setTime = (select subtime(now(),'00:02:00'));
insert into sequence (name,deposit_date,deposit_amount,interest_amount) values ('이소윤',@setTime,10000000,0);





drop procedure if exists pro;
delimiter //
create procedure pro()
begin
DECLARE n varchar(45) default "이소윤" ;

while (select id from sequence order by id desc limit 1) < 10 do
INSERT INTO sequence (deposit_date) select (date_add((select deposit_date from sequence where  deposit_date order by id desc limit 1),INTERVAL 1 hour));

update sequence 
set 
name = n,
interest_amount =  (select deposit_amount where  deposit_amount order by id desc limit 1)* 0.04 /12;




end while;

end //
delimiter ;
call pro();

select * from test.sequence;


 

---

시간 증가만 insert해주고

나머지는 update로 넣어주려 했으나 잘안됨..

그래서 원래 한번에 다 insert한 걸로 수정함

 

중간에 null인거..

 

 

그냥 id가 2인거 조건으로 넣어줌..

이러면 안될거같지만

use test;
truncate sequence;


set @setTime = (select subtime(now(),'00:02:00'));

insert into sequence (name,deposit_date,deposit_amount,interest_amount) values ('이소윤',@setTime,10000000,0);

drop procedure if exists pro;
delimiter //
create procedure pro()
begin
while (select id from sequence order by id desc limit 1) < 10 do


INSERT INTO sequence (name,deposit_date,deposit_amount,interest_amount) 
select 
(select name from sequence order by id desc limit 1),
date_add((select deposit_date from sequence where  deposit_date order by id desc limit 1),INTERVAL 1 hour),
((select deposit_amount from sequence where  deposit_amount order by id desc limit 1) + (select interest_amount from sequence where  interest_amount order by id desc limit 1)),
(select deposit_amount from sequence where id='1')* 0.04 /12;


end while;
end //
delimiter ;

call pro();

update sequence 
set deposit_amount = 10000000
where id = 2;


select * from sequence;

 

 

 order by limit 1

를 쓰는 것보다 max가 좀더 빠르다는 얘기를 들음

내일 수정해봐야겠다

 

728x90
728x90

https://stepby-yun.tistory.com/185

 

mysql 이자액 계산기 식 만들기 (값 띄우기select,넣기insert,삭제TRUNCATE)

목표 년 이자 4프로를 12개월로 나눠서 매월 찍히는걸로 하는건데 이름은 그대로 입금날짜는 한달씩 증가로 찍혀야함!! 이자율 계산 INSERT INTO test.sequence (interest_amount) SELECT (deposit_amount ..

stepby-yun.tistory.com

 

지난시간..

복잡한 식을 깔끔하게 만들어주고자 변수를 사용해봤다.

 

 

(찾아보니까 declare(타입선언)랑 set(변수할당)있었는데 어째서인제 declare은 자꾸 빨간선뜸.

변수 설정할때 @이름 으로 씀)

 

use test;
insert into sequence (name,deposit_date,deposit_amount) values ('이소윤',now(),'10000000');

set @lastDate = (select deposit_date from sequence order by id desc limit 1) ;
set @initial_amount = (select deposit_amount from sequence where id='1');
set @name = (select name from sequence where id='1');


INSERT INTO sequence (name,deposit_date,interest_amount)
select @name,
 (select date_add(@lastDate,INTERVAL 1 MONTH)),
@initial_amount* 0.04 /12;

 

 

 

하.지.만.

 

 

마지막 행 날짜값에다가 한달씩 더해야되는데 

자꾸 첫번째 행값에 더했다.

 

 

 

 

 

예상했던대로 변수 재할당 다시 해야만 

마지막 값을 가져왔다. 허허...

 

어떻게 해결할 것인가~ 

 

 

 

만약에 행이 추가되면 변수 재할당으로 해야하나????

???

 

 

 

 

728x90
728x90

따라하면서

순서, 필요한 내용 적기 

<이 순간, 최고의 강의_별점 백개 드립니다_>

https://www.youtube.com/watch?v=re3OIOr9dJI 

 

client -react 프론트

server -express, 백단

 

client/ npx create-react-app .

(.은 현재 위치를 의미함)

server/ npm init 

해서 package.json 생성하고

필요한 

mysql express 

설치

 

client/

Login.js

import { useState } from "react";
import "./login.css";

function Login() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState("");
  const [position, setPosition] = useState("");
  const [wage, setWage] = useState(0);

  const onChangefun = (event) => {
    setName(event.target.value);
    console.log(event.target.value);
  };
  return (
    <div className="login">
      <div className="information">
        <label>Name : </label>
        <input type="text" onChange={onChangefun}></input>
        <label>Age : </label>
        <input
          type="number"
          onChange={(event) => {
            setAge(event.target.value);
          }}
        ></input>
        <label>Country : </label>
        <input
          type="text"
          onChange={(event) => {
            setCountry(event.target.value);
          }}
        ></input>
        <label>Position : </label>
        <input
          type="text"
          onChange={(event) => {
            setPosition(event.target.value);
          }}
        ></input>
        <label>Wage: </label>
        <input
          type="number"
          onChange={(event) => {
            setWage(event.target.value);
          }}
        ></input>
        <button>직원 등록</button>
      </div>
    </div>
  );
}

export default Login;

 

server/

index.js

const express = require("express");
const app = express();

app.listen(3001, () => {
  console.log("your server is running on 3001~! yeah");
});

 

이제 mysql 설정해줄거임

 

mysql 워크벤치에서 

스키마 생성

테이블 생성

server/

디비저장 코드 입력

 

const express = require("express");
const app = express();
const mysql = require("mysql");

const db = mysql.createConnection({
  user: "root",
  host: "localhost",
  password: "비밀번호",
  database: "crudtest",
});

app.post("/create", (req, res) => {
  const name = req.body.frontname;
  const age = req.body.frontage;
  const country = req.body.frontcountry;
  const position = req.body.frontposition;
  const wage = req.body.frontwage;

  db.query(
    "INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?)",
    [name, age, country, position, wage],
    //콜백함수
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send("values Inserted");
      }
    }
  );
});

app.listen(3001, () => {
  console.log("your server is running on 3001~! yeah");
});

client/

import { useState } from "react";
import "./login.css";
import Axios from "axios";

function Login() {
  const [name, setName] = useState("");
  const [age, setAge] = useState(0);
  const [country, setCountry] = useState("");
  const [position, setPosition] = useState("");
  const [wage, setWage] = useState(0);

  const addEmployee = () => {
    Axios.post("http://localhost:3001/create", {
      frontname: name,
      frontage: age,
      frontcountry: country,
      frontposition: position,
      frontwage: wage,
    }).then(() => {
      console.log("success");
    });
  };

  const onChangefun = (event) => {
    setName(event.target.value);
    console.log(event.target.value);
  };
  return (
    <div className="login">
      <div className="information">
        <label>Name : </label>
        <input type="text" onChange={onChangefun}></input>
        <label>Age : </label>
        <input
          type="number"
          onChange={(event) => {
            setAge(event.target.value);
          }}
        ></input>
        <label>Country : </label>
        <input
          type="text"
          onChange={(event) => {
            setCountry(event.target.value);
          }}
        ></input>
        <label>Position : </label>
        <input
          type="text"
          onChange={(event) => {
            setPosition(event.target.value);
          }}
        ></input>
        <label>Wage: </label>
        <input
          type="number"
          onChange={(event) => {
            setWage(event.target.value);
          }}
        ></input>
        <button onClick={addEmployee}>직원 등록</button>
      </div>
    </div>
  );
}

export default Login;

프런트에서 백 전달할때 

우리는 api허용해주기 위해서 cors 라이브러리 사용할거임

npm i cors

 

server/ index.js 파일에

const cors = require("cors");
app.use(cors());

추가

 

 

 

 

근데 여전히 막상보면 백으로 못넘어옴

이렇게 req.body 콘솔 찍어보면 

undefined 뜸 

 

json 미들웨어를 제공안해서였음

프런트에서 보낼때 

 

 

index.js/

app.use(express.json());

이거 추가

 

유튜브영상에서는 이거 추가하면 db넣기 성공했는데 난 안됨. ㅎ

 

 db에 안들어가고 

에러 뜸

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

 

 

이거 mysql에 외부접근안돼서 그런거라고 함  

그래서 이걸로 해결가능하다고 함( 비번 사용해서 db계정사용하게끔 하는 설정인듯!)

 

+해결방법중에 mysql2쓰는 것도 있음 이번에는 안해봄 

 ALTER user '[유저]'@'localhost' IDENTIFIED WITH mysql_native_password by '[비번]';

 바꿔주기 위해서 mysql로 ㄱㄱ

mysql에 바로 use mysql하면 접속이 안됨

mysql -u root -p도 당연히 안됨

 

 

'use'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다

워크벤치 경로로 들어가서 해야함~~~

C:\Program Files\MySQL\MySQL Server 8.0\bin

 

 

cd C:\Program Files\MySQL\MySQL Server 8.0\bin

mysql -u root -p

 

이제 mysql켜짐

 

mysql>

 

 

계정 뭐있는지 확인 먼저 함

 

SELECT user,authentication_string,plugin,host FROM mysql.user;

 

내가 쓸 root계정 있는거 확인함

 

 

 

 

 ALTER user '[유저]'@'localhost' IDENTIFIED WITH mysql_native_password by '[비번]';

 

flush privileges;

 

 

 

index.js 

서버 끄고 다시 실행

node index.js

로 실행

 

 

직원등록 눌러서 보내보면 

 

잘 들어왔다~!~!~!~!~!

 

 

 

이제 우리가 할거는

백-> 프런트로 

정보 가져오는걸 할거임

우리는 필요할 때 정보를 봐야하니까 

 

 

client/

//초기에는 빈배열이니까 []로 넣어줌 
 const [employeesList, setEmployeesList] = useState([]);
 //가져올 함수// 백가져온 응답반은걸 콘솔로 보여주겠음 response가져온거의 data로
   const getEmployee = () => {
    Axios.get("http://localhost:3001/employees").then((response) => {
      setEmployeesList(response.data);
    });
  };
  
  
 //버튼
   <div className="showDB">
      //버튼눌렀을 때 가져올 함수 실행
        <button className="showDB-button" onClick={getEmployee}>
          show employees
        </button>
      </div>

 

server/

app.get("/employees", (req, res) => {
//db에서 employess테이블 다 가져와
  db.query("SELECT * FROM employees", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

버튼 누르면

이건 response임 

object 객체로 가져옴

(status 200 -> 작동한거임)

이안에 우리가 원하는 정보가 잘 담겨져있음

 

 

이제 백에서 가져온 것들을 화면에 띄워줄거임

맵함수 사용해서

배열에서 하나씩 꺼내오기 

 

        <div>
          {employeesList.map((val, index) => {
            return (
              <div className="employee">
                <h3>{val.name}</h3>
                <h3>{val.age}</h3>
                <h3>{val.country}</h3>
                <h3>{val.position}</h3>
                <h3>{val.wage}</h3>
              </div>
            );
          })}
        </div>

성공~~~

 

 

근데 다른 방법도 있대 

post에 넣고 바로 화면에 띄우게 하는법

 

const addEmployee = () => {
    console.log(name, "dfdfd");
    Axios.post("http://localhost:3001/create", {
      frontname: name,
      frontage: age,
      frontcountry: country,
      frontposition: position,
      frontwage: wage,
    }).then(
      //   () => {
      //   console.log("success");
      // }
      () => {
        //기존 배열에 방금 입력한 걸 추가하고 그걸 setEmployessList함수에 넣음! 배경은 뜨는데 값이 안띄워지네..흠
        //암튼 여러 방법이 있다고 함 있다가 해보자
        setEmployeesList([
          ...employeesList,
          {
            frontname: name,
            frontage: age,
            frontcountry: country,
            frontposition: position,
            frontwage: wage,
          },
        ]);
      }
    );
  };

나는 왜인지 빈값만 뜸

 

db에는 잘들어갔는데...

왜 안뜨는 것인가...

이부분은 다른 날에 해보겟음

 

 

이제 

삭제 하고 수정하고 다음에 해봐야지

db에서 가져온 목록 선택해서 나열하게 하고

이런 것도 해보고 싶네 

 

아 그리고 지금은 새로고침하면 db에서 블러온 애들이 화면에서 사라지거든

그것도 막아야겠다.

728x90
728x90

https://dukdukz.tistory.com/entry/210604-Sequelize-auto-%EB%A1%9C-%ED%85%8C%EC%9D%B4%EB%B8%94-%EC%83%9D%EC%84%B1-%EA%B5%AC%EB%AC%B8-%EB%A7%8C%EB%93%A4%EA%B8%B0

https://www.hanumoka.net/2018/11/23/node-20181123-express-setting-sequelize/

 

Node Express에 sequelize를 이용해 mysql접속하기

들어가기Express 프로젝트에 sequelize(시퀄라이저)를 이용하여 로컬에 있는 mysql에 접속하는 예제를 정리해본다. 미리 로컬에 mysql을 설치하고, 스키마와 계정을 생성 해놨다. 테스트용 Express 프로젝

www.hanumoka.net

MySql에서 워크벤치로 테이블구성을 다 하고 

코드에서 시퀄라이즈 연동을 하려니까 번거로웠다. 뿐만 아니라 타입이 일치한데 해당하는 테이블을 찾을 수 없다고 연결이 안돼서 답답했다. 찾아보니 역시 자동으로 구성된 테이블 코드를 짜주는 방법이 있었다!!

 

나는 EER 에서 다이어그램으로 테이블을 먼저 짰다.

그리고 Forward Enginner를 누르면 

만든 다이어그램이 테이블로 생성이 된다. (Synchronize Model하면 기존에 있는 테이블을 수정하고 업데이트할 수 있다.)

 

 

이제 코드에서 만져보자

 

시퀄라이즈 세팅을 먼저 한다. 

(npm i express

npm i -D nodemon

)

npm i sequelize //시퀄라이즈

npm i mysql2   //mysql과 시퀄라이즈를 이어주는 드라이버이다. 

npm i sequelize-cli   //시퀄라이즈 명령어를 실행하기 위한 패키지다

 

npx sequelize init //하면 기본 폴더가 생성된다.

이제 자동으로 db테이블 코드가져와주는

npm i sequelize-auto

를 깐다. 

 

터미널에 명령어를 입력한다.

npx sequelize-auto -o "./models" -d nodejs -h "localhost" -u "root" -p "3306" -x "비밀번호" -e mysql

 

 

-o "경로"
-d "db 이름"
-h "url"->localhost
-u "root"
-p "port"
-x "password"
-e "mysql"

 

 

그럼 필요한 user, music,artist 코드가 자동으로 생긴다. 

근데 문제는 코드가 좀 다르다 function이다.

 

내가 db구조 짤때 참고한 nodejs책에서는 class로 해서 

안에 내용을 기존에 참고했던 식으로 바꿔줬다. 큰틀만 바꾸면 됨

artist.js

그리고 init-model.js도 생겼는데

나는 index.js로 작업하고 잘모르겠고 구조도 바꿔줘서 

주석처리했다. 

대신 관계정의할 때 필요한 것들은 참고해서 넣었다.

artist.js

수정한다음에 혹시몰라서 

워크벤치에 있는 database를 삭제하고

 

npx sequelize db:create로 다시 db를 만들고

npm start 실행했다. 

 

연결잘된다. 

 

 

(

문제는 내가 원하는건 user랑 artist의 1대1관계인데

분명 user에 hasOne, artist에 belongsTo로 줬는데 

왜 다이어그램을 뽑아보면 1대다로 나오는지 모르겠다....)

 

 

 

 

그리고 일대다에도 종류가 두개있어서 놀람

https://jins-dev.tistory.com/entry/RDBMS%EC%9D%98-%EA%B4%80%EA%B3%84-Identifying-NonIdentifying-Relationship-%EC%97%90-%EB%8C%80%ED%95%98%EC%97%AC

 

RDBMS의 관계 - Identifying & Non-Identifying Relationship 에 대하여

 RDB에서 관계를 맺는데 있어서 식별관계(Identifying Relationship)와 비식별관계(Non-Identifying Reltationship)가 존재한다. 정확히는 RDBMS에서 나누는 관계가 아닌 ER Diagram 상에서 논리상 나누는 개념이..

jins-dev.tistory.com

 

이건그냥 공식문서 필요할때 보라고 넣어둠

https://sequelize.org/master/manual/legacy.html

 

Manual | Sequelize

Working with Legacy Tables While out of the box Sequelize will seem a bit opinionated it's easy to work legacy tables and forward proof your application by defining (otherwise generated) table and field names. Tables class User extends Model {} User.init({

sequelize.org

 

728x90

+ Recent posts