python - 通过 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)
解决方案
正如我在聊天中建议的那样,我认为您应该使用 Azure 数据工厂将数据从数据库复制到平面文件。
推荐阅读
- java - 解密问题,android AES/CTR/NoPadding 中的密码
- javascript - Card Img Overlay,溢出卡体
- python-3.x - 删除前 x 个百分位数数据后重新采样时间序列
- javascript - 我的数据库中的数据未显示在 jQuery 数据表中
- javascript - 如何在不影响其余子元素的情况下仅使一个子元素具有粘性?
- mysql - 如何将一些表信息插入另一个表列?
- nlog - NLog.config 文件不是根目录中的字符串。而是在发布时存储在 bin 目录中
- microsoft-cognitive - 如何使用 Form-Recognizer Microsoft-Cognitive 分析来自 blob 的文档?
- node.js - Sequelize - 保存父母时设置孩子的外键
- javascript - 嵌入的 YouTube 视频上的 rel=0 不起作用?