Python

Python MySQL Connector를 이용해 delete하기 - delete메소드

Cong_S 2022. 6. 19. 18:26
pip install flask
pip install flask-restful
pip install mysql-connector-python

 

미리 설치할 라이브러리

 

use mysql;

create user 'recipe_user'@'%' identified by '1q2w3e4r';

grant all on recipe_db.* to 'recipe_user'@'%';

 

 

먼저 특정 유저만 DB에 접속할 수 있도록 새로운 계정을 만듬.

 

import mysql.connector

def get_connection():
    connection = mysql.connector. connect(
        host = 'host.ctttsro2er9u.ap-northeast-2.rds.amazonaws.com',
        database = 'recipe_db',
        user = 'recipe_user',
        password = '1q2w3e4r'
    )
    return connection

 

다음 파이썬 환경에서 새로운 py 파일을 만들어 위와 같은 함수를 만들어 놓음

위에서 만든 계정을 통해 특정 DB만 접속하도록 만든 것임.

 

app = Flask(__name__)

api = Api(app)

# 경로와 리소스(API 코드)를 연결한다.
api.add_resource(RecipeListResource, '/recipes')
api.add_resource(RecipeResource, '/recipes/<int:recipe_id>')


if __name__=='__main__':
    app.run()

 

다음 메인 파일에서 class로 상속받아 리소스를 추가해준다.

 


파이썬으로 데이터베이스에 데이터 delete 하기

 

상속해준 class가 있는 파일로 와서

# 삭제하는 delete 함수    
    def delete(self, recipe_id):
        try :
            # 데이터 업데이트 
            # 1. DB에 연결
            connection = get_connection()

            # 2. 쿼리문 만들기
            query = '''delete from recipe
                        where id = %s;'''
            
            record = (recipe_id, )

            # 3. 커서를 가져온다.
            cursor = connection.cursor()

            # 4. 쿼리문을 커서를 이용해서 실행한다.
            cursor.execute(query, record)

            # 5. 커넥션을 커밋해줘야 한다 => 디비에 영구적으로 반영하라는 뜻
            connection.commit()

            # 6. 자원 해제
            cursor.close()
            connection.close()

        except mysql.connector.Error as e :
            print(e)
            cursor.close()
            connection.close()
            return {'error' : str(e)}, 503

        return {'result' :'success'}, 200

다음과 같은 순서로 코드를 작성한다. 

그 후 서버를 실행한 후 포스트맨에서 원하는 주소로 Send 하면 된다.

 

해당 코드로 작성했을 시 결과에 succes와 코드 200이 나오면 정상적으로삭제된 것이다.