使用Boto3与RDS上的amazon Aurora进行交互

时间:2016-02-17 21:42:36

标签: python mysql amazon-web-services boto3

我使用Amazon Aurora在Amazon RDS中设置了一个数据库,并希望使用Python与数据库进行交互 - 显而易见的选择是使用Boto。

但是,他们的文档非常糟糕,并且我可以通过覆盖方式与数据库进行交互:

  • 使用SQL语句运行查询
  • 与数据库中的表进行交互

有没有人有一些示例/教程的链接,或者知道如何执行这些任务?

2 个答案:

答案 0 :(得分:11)

使用Amazon RDS产品(包括Aurora)时,您无法通过任何AWS API(包括Boto)连接到数据库。相反,您将使用所选数据库的本机客户端。对于Aurora,您将使用MySQL命令行客户端进行连接。从那里,您可以像任何其他MySQL数据库一样查询它。

这是"入门"的简要部分。有关连接Aurora数据库的文档:

Connecting to an Amazon Aurora DB Cluster

答案 1 :(得分:3)

以下是几个例子:

插入示例:

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