본문 바로가기

프론트앤드 수업

[React] mysql React , select, insert, update, delete문 사용

728x90

사용할 테이블

 


Select문

1. react에서 경로/요청구문을 작성해 서버에 자료를 요청한다.

async function getCustomer(){
const customers = await axios.get(`http://localhost:3001/customers`)
  return customers.data;
}

/customers로 요청하였다.
2. 서버에서 요청구문으로 값을 받은 후 돌려보낼 자료를 리턴해준다.

app.get('/customers', async (req,res) => {
    connection.query(
        "select * from customers_table",
        (err,rows,fields)=>{
            res.send(rows);
        }
    )
})

rows전체를 보내주도록 한다. 테이블의 모든 자료가 들어감
3. 받은 값을 이용해 데이터를 넣어준다. 객체이기에 객체별로 하나씩 넣어줄 수 있다.
※ 받아오는 값은 객체가아니라 배열이니 배열로 사용한다고 생각해야함. (map 사용)

const Customer = ({customer}) => {
    return (
            <TableRow>

        <TableCell>{customer.no}</TableCell>
        <TableCell><Link to={`/detailview/${customer.no}`}>{customer.name}</Link></TableCell>
        <TableCell>{customer.phone}</TableCell>
        <TableCell>{customer.birth}</TableCell>
        <TableCell>{customer.gender}</TableCell>
        <TableCell>{customer.add1}</TableCell>
      </TableRow>
    )
};

받아온 데이터자료.

 

 


 

Insert문

1. 키값과 값을 관리할 객체를 선언하고 input에서 값을 받아오도록 한다.

 const [formData, setFormData] = useState({
        c_name:  "",
        c_phone:  "",
        c_birth:  "",
        c_gender: "",
        c_add: "",
        c_adddetail: ""
    })
    const onChange =(e) => {
        const {name, value} = e.target;
        setFormData({
            ...formData,
            [name]:value
        })
    }
  1. 값들을 post로 전송하고 역시 요청구문을 작성해 서버로 전송한다.
function insertCustomer(){ axios.post("http://localhost:3001/createcustom",formData) 
.then(result => { console.log("성공") navigate("/"); }) 
.catch(e => { console.log(e) }) }
  1. post로 전송받은 데이터를 받아오고 insert문으로 넣어준다.inset문에서 value값을 ? 로 지정하고 ,다음 배열식으로 한번에 다 넣을 수 있다.
    받아온값은 req.body에 저장되지만 그대로사용하면 req.body.cname으로 사용해야하는 번거로움이 있으니 body라는 변수에 한번 넣어 사용했다.
app.post('/createcustom', async (req,res) => 
{ const body = req.body; connection.query( "insert into customers_table 
(`name`, `phone`, `birth`, `gender`, `add1`, `add2`) value(?,?,?,?,?,?)", [body.c_name,body.c_phone,body.c_birth,body.c_gender,body.c_add,body.c_adddetail], 
(err,rows,fields)=>{ if (err) { console.log("DB저장 실패"); }else{ console.log("DB저장 성공"); };} 
) 
})

 


Delete문

  1. 클릭되는 삭제구문에 Link나 다른구문으로 선택해야할 id값이나 primary key가되는 필드값을 넘겨주고 App에서의 path값에 :id 같이 get으로 받아올수 있도록 만들어준다.
<Routes> <Route path="/" element={<CustomerList customers={data}/>}/> 
<Route path="/detailview/:id" element={<DetailCustomer/>} /> 
<Route path="/EditCustomer/:id" element={<EditCustomer/>} /> 
<Route path="/write" element={<CreateCustomer/>} /> 
</Routes>

2.딜리트의구문은 axios.delete이며 id값과 사용할 구문으로 서버로 넘겨준다.

:id로 값을 Params로 받아옴. const DetailCustomer = () => 
{ const { id } = useParams(); 
const navigate = useNavigate(); //삭제하기 
const onDelete = () => { axios.delete(`http://localhost:3001/delCoustomer/${id}`) 
.then(result=>{ console.log("삭제되었습니다.") navigate("/"); }) 
.catch(e => console.log(e)) }
  1. 서버로 돌아와 delete로 요청한 데이터와 params값을 수령해 해당 데이터자료를 삭제해준다.
    ※params는 바로 id값이 들어가있는게아니라 params객체 안의 .id나 보내준 이름에 값이 들어있으니 주의하도록 한다.
    삭제구문과 같이 id값을보내 select 전체구문을 출력하듯 똑같이해서 하나의 데이터만 출력할 수 있다.
  2. app.delete(`/delCoustomer/:id` , async(req, res) => { const params = req.params; connection.query( `delete from customers_table where no =${params.id}` ,(err,rows,fields)=>{ res.send(rows); console.log('삭제완료'); })

 


Update문

수정구문은 조금 복잡하다.

  1. 수정을 시작할때 원레 들어가있던 값을 기본적으로 넣어놓기 위해 삽입에 사용했던 객체데이터를 가져온다.
  2. const [formData, setFormData] = useState({ c_name: "", c_phone: "", c_birth: "", c_gender: "", c_add: "", c_adddetail: "" })
  3. Params를 이용해 해당값만 가져오도록 하고 input에 넣어주도록한다. 한줄만 넣어놓겠음..defaultValue를 사용할시 처음 화면이 로딩될때 1회만 해당값이 들어간다.(수정가능) value를 사용시 해당값이 수정되지 않는다.(새로운 state를 사용해야함)
async function getCustomer(id){ const customer = await axios.get(`http://localhost:3001/customer/${id}`) 
return customer.data } //필요한값 받아오기 const { id } = useParams(); 
<input name="c_name" type='text' defaultValue={data.name}
  1. 값이 수정되면 새로이 값을 넣어줘야하니 setstate를 이용해 수정해준다.useEffect가 데이터로딩이 모두 끝난 후 적용되야하는데 그냥입력 시 없는 데이터값을 받아와서 에러가 발생한다.
    해당 에러를 막기위해 삼항연산자를 이용해 데이터가 있다면 해당내용을 실행하도록 설정
useEffect(()=>{ setFormData({ c_name: data? data.name : "", c_phone: data? data.phone : "", 
c_birth: data? data.birth : "", c_gender: data? data.gender : "", c_add: data? data.add1 : "", 
c_adddetail: data? data.add2: "" }) },[data])
  1. 수정완료된 값을 서버로 전송해준다. 구문은 put을 이용한다.(수정)
  const onEdit = () => {
        axios.put(`http://localhost:3001/editcustom/${id}`,formData)
        .then(result => {
            navigate("/");
        })
        .catch(e => {
            console.log(e)
        })
    }
  1. 서버에서 값을 받아와 Update구문을 작성해준다.
app.put('/editcustom/:id', async (req,res) => {
    const params1 = req.params;
    const body= req.body;
    connection.query(
        `update customers_table set name = '${body.c_name}', phone = '${body.c_phone}', birth = '${body.c_birth}',
        gender = '${body.c_gender}', add1 = '${body.c_add}', add2 = '${body.c_adddetail}' where no = ${params1.id}`,
        (err,rows,frelds) => {
            if(err) {
                console.log(err)
            }else{
                console.log("성공")
            }
        }
    )
})

Update구문의 실수나 오타로인해 엄청난 스트레스를 받을 수 있으니 주의해서 작성하도록 한다...
꼭 post man으로 테스트해보길..

728x90
댓글