当前位置: 首页 > 工具软件 > PyAthena > 使用案例 >

通过pyathenajdbc访问aws athena

黎阳冰
2023-12-01

下面帖子的内容基于网上其它博友的帖子,原帖子的代码执行失败,估计与版本有关。在原帖子的基础上进行了修改。原帖子的链接为:aws之athena使用_weixin_43843414的博客-CSDN博客

# cat test1.py
#coding:utf-8

#Using JDBC
import os
import configparser
import pyathenajdbc

# Get aws credentials
Config = configparser.ConfigParser()
Config.read(os.path.expanduser('~/.aws/credentials'))

# 如果不设置环境变量,程序也会自动从上面所示文件中读取的;如果设置了环境变量则不会从文件读取
os.environ['AWS_ACCESS_KEY'] = Config['default']['aws_access_key_id']
os.environ['AWS_SECRET_KEY'] = Config['default']['aws_secret_access_key']

class PyAthenaLoader():

    def connect(self):
        # 网上很多帖子,connect请求参数与下面是不同的
        self.conn = pyathenajdbc.connect(
            # S3上指定一个路径,用于临时保存sql语句执行的结果,不用担心会被自动清除的
            S3OutputLocation="s3://xxx/db_log/",
            AwsRegion="ap-southeast-1"
        )

    def query(self, req):
        self.connect()

        try:
            with self.conn.cursor() as cursor:
                cursor.execute(req)
                res = cursor.fetchall()
        except Exception as X:
            return X
        finally:
            self.conn.close()
        return res

athena = PyAthenaLoader()
print(athena.query('SELECT * FROM test_db.test_table limit 10;'))

 类似资料: