簡體   English   中英

在 RDS 上使用 Boto3 與亞馬遜 Aurora 交互

[英]Using Boto3 to interact with amazon Aurora on RDS

我已經使用 Amazon Aurora 在 Amazon RDS 中設置了一個數據庫,並希望使用 Python 與該數據庫進行交互 - 顯而易見的選擇是使用 Boto。

然而,他們的文檔很糟糕,並沒有涵蓋我可以與數據庫交互的方式:

  • 使用 SQL 語句運行查詢
  • 與數據庫中的表進行交互
  • 等等

有沒有人有一些示例/教程的鏈接,或者知道如何完成這些任務?

使用 Amazon RDS 產品(包括 Aurora)時,您不會通過任何 AWS API(包括 Boto)連接到數據庫。 相反,您將使用所選數據庫的本機客戶端。 對於 Aurora,您將使用 MySQL 命令行客戶端進行連接。 從那里,您可以像查詢任何其他 MySQL 數據庫一樣查詢它。

“入門”文檔中有一個簡短的部分討論了連接到您的 Aurora 數據庫:

連接到 Amazon Aurora 數據庫集群

這里有幾個例子:

插入示例:

import boto3

sql = """
        INSERT INTO YOUR_TABLE_NAME_HERE
        (
            your_column_name_1
            ,your_column_name_2
            ,your_column_name_3)
        VALUES(
            :your_param_1_name
            ,:your_param_2_name)
            ,:your_param_3_name
        """

param1 = {'name':'your_param_1_name', 'value':{'longValue': 5}}
param2 = {'name':'your_param_2_name', 'value':{'longValue': 63}}
param3 = {'name':'your_param_3_name', 'value':{'stringValue': 'para bailar la bamba'}}

param_set = [param1, param2, param3]

db_clust_arn = 'your_db_cluster_arn_here'

db_secret_arn = 'your_db_secret_arn_here'

rds_data = boto3.client('rds-data')

response = rds_data.execute_statement(
    resourceArn = db_clust_arn, 
    secretArn = db_secret_arn, 
    database = 'your_database_name_here', 
    sql = sql,
    parameters = param_set)

print(str(response))

閱讀示例:

import boto3

rds_data = boto3.client('rds-data')

db_clust_arn = 'your_db_cluster_arn_here'

db_secret_arn = 'your_db_secret_arn_here'


employee_id = 35853

get_vacation_days_sql = f"""
    select vacation_days_remaining
    from employees_tbl
    where employee_id = {employee_id}    
        """


response1 = rds_data.execute_statement(
        resourceArn = db_clust_arn, 
        secretArn = db_secret_arn, 
        database = 'your_database_name_here', 
        sql = get_vacation_days_sql)

#recs is a list (of rows returned from Db)
recs = response1['records']

print(f"recs === {recs}")
#recs === [[{'longValue': 57}]]

#single_row is a list of dictionaries, where each dictionary represents a 
#column from that single row
for single_row in recs:
    print(f"single_row === {single_row}")
    #single_row === [{'longValue': 57}]
    
    #one_dict is a dictionary with one key value pair
    #where the key is the data type of the column and the 
    #value is the value of the column
    #each additional column is another dictionary
    for single_column_dict in single_row:
        print(f"one_dict === {single_column_dict}")
        # one_dict === {'longValue': 57}

        vacation_days_remaining = single_column_dict['longValue']
        
        print(f'vacation days remaining === {vacation_days_remaining}')

源鏈接: https : //docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html#data-api.calling.python

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM