如何使用 Boto3 從 AWS 資料目錄中刪除資料庫?


問題陳述 − 使用 Python 中的 boto3 庫刪除在您的賬戶中建立的資料庫。

示例 − 刪除在您的賬戶中建立的資料庫“Portfolio”。

解決此問題的方法/演算法

步驟 1 − 匯入 boto3 和 botocore 異常以處理異常。

步驟 2 − 傳遞要從 AWS Glue Catalog 中刪除的database_name引數。

步驟 3 − 使用 boto3 庫建立 AWS 會話。確保在預設配置檔案中提到了 region_name。如果未提及,則在建立會話時顯式傳遞 region_name。

步驟 4 − 為 Glue 建立 AWS 客戶端。

步驟 5 − 現在使用 delete_database 函式並將 database_name 作為 Name 引數傳遞。

步驟 6 − 它將刪除資料庫並返回響應元資料。

步驟 7 − 如果在檢查作業時出現問題,則處理通用異常。

注意:此操作完成後,使用者將無法訪問已刪除資料庫中的表(以及屬於這些表的全部表版本和分割槽)和使用者定義函式(儲存過程)。AWS Glue 將及時非同步刪除這些“孤立”資源,具體時間由服務自行決定。

示例

使用以下程式碼從 AWS Glue 資料目錄中刪除資料庫:

import boto3
from botocore.exceptions import ClientError

def delete_a_database(database_name):
   session = boto3.session.Session()
   glue_client = session.client('glue')
   try:
      response = glue_client.delete_database(Name=database_name)
   return response
   except ClientError as e:
      raise Exception( "boto3 client error in delete_a_database: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in delete_a_database: " + e.__str__())

print(delete_a_database("Portfolio"))

輸出

{'ResponseMetadata': {'RequestId': '067b667f-0a74d4f30a5b',
'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sat, 27 Feb 2021
14:54:30 GMT', 'content-type': 'application/x-amz-json-1.1', 'contentlength': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '067b667f0a10-4f99-91be-0a74d4f30a5b'}, 'RetryAttempts': 0}}

更新於:2021年3月22日

354 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告