首页 > 解决方案 > 通过 Python 将 postgres 数据复制到 ADLS 的有效方法

问题描述

我正在从 Postgres 表中读取数据,我需要在 ADLS 中写入相同的数据。我目前的方法是读取表,将结果存储到本地文件中,然后将本地文件写入 Azure 数据湖。

请让我知道是否可以在没有临时本地文件的情况下从 postgres 直接将数据写入 ADLS。

出于测试目的,我以 csv 格式移动数据。如果我能够跳过中间本地文件,我也可以使用镶木地板或兽人格式。

我当前的工作代码:

import psycopg2
from azure.storage.filedatalake import FileSystemClient

conn_Str = "conn_Str"
file_system = FileSystemClient.from_connection_string(conn_Str, file_system_name="file_system_name")

try:

    connection = psycopg2.connect(database="db",user="usr",password="pwd",host="localhost")
    cursor = connection.cursor()
    sql = "COPY (select * from schema.table) TO STDOUT WITH CSV DELIMITER ';'"
     with open(r"/dir1/dir2/table.csv", "w") as file:
        cursor.copy_expert(sql, file)
        print ("file written")
        
except (Exception, psycopg2.Error) as error:
    print("Error while fetching data from PostgreSQL", error)

finally:
    # closing database connection.
    if connection:
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")
#Writing the local file to ADLS
file_system = FileSystemClient.from_connection_string(conn_Str, file_system_name="container")
directory_client = file_system.get_directory_client("dir1/subdir")
file_client = directory_client.get_file_client("table-file.csv")
local_file = open(r"/dir1/dir2/table.csv",'r')
file_contents = local_file.read()
file_client.upload_data(file_contents, overwrite=True)

标签: pythonpostgresqlazureazure-data-lakeazure-data-lake-gen2

解决方案


正如我在聊天中建议的那样,我认为您应该使用 Azure 数据工厂将数据从数据库复制到平面文件。


推荐阅读