How to Connect to Athena with Python?

Estimated read time 2 min read

To connect to Amazon Athena using Python, you can use the pyathena library, which provides a Python DB API 2.0 (PEP 249) compatible interface for interacting with Athena. Here’s an example of how you can establish a connection to Athena and execute a query:

import pyathena

# Create a connection to Athena
conn = pyathena.connect(
    region_name='your_aws_region',
    access_key='your_aws_access_key',
    secret_key='your_aws_secret_key'
)

# Create a cursor object
cursor = conn.cursor()

# Execute a query
query = 'SELECT * FROM your_database.your_table LIMIT 10'
cursor.execute(query)

# Fetch and print the results
results = cursor.fetchall()
for row in results:
    print(row)

# Close the cursor and connection
cursor.close()
conn.close()

In this example, you need to replace 'your_aws_region', 'your_aws_access_key', and 'your_aws_secret_key' with your actual AWS region and access credentials.

After creating a connection using pyathena.connect(), you can create a cursor object using conn.cursor() to execute queries. In this example, we execute a sample query to select data from a table.

To fetch the results, you can use the fetchall() method of the cursor. You can iterate over the rows and print them or perform any desired processing.

Finally, make sure to close the cursor and connection using cursor.close() and conn.close() to free up resources.

Note: To use the pyathena library, you need to install it first. You can install it using pip:

pip install pyathena

Also, ensure that you have the necessary AWS credentials and permissions to access Athena.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply