Restful API

[Restful API] Python MySQL Connector delete

건휘맨 2024. 5. 21. 16:48

포스트맨에서 DELETE 로 설정하고 URL을 입력

GET과 DELETE는 Body를 설정하지 않는다.

Visual Studio Code에서 코드 작성

변경 사항은 실제로는 데이터베이스에 반영되기 전에 메모리에만 저장된다.

이렇게 메모리에 저장된 변경 사항을 데이터베이스에 영구적으로 적용하기 위해 commit()을 호출한다.

class RecipeResource(Resource):

    def delete(self, recipe_id):

        print(recipe_id)

        try:
            connection = get_connection()
            query = '''delete from recipe
                        where id = %s;'''
            record = (recipe_id, )
            cursor = connection.cursor()
            cursor.execute(query, record)

	# 메모리에 저장된 변경 사항을 데이터베이스에 적용하기 위해 commit()
            connection.commit()
            
            cursor.close()
            connection.close()

        except Error as e:
            if cursor is not None:
                cursor.close()
            if connection is not None:
                connection.close()
            return {"result" : "fail", 
                    "error" : str(e)}, 500
        
        return {"result" : "success"}

 

데이터가 삭제 되었는지 MySQL Workbench에서 확인한다.