我是靠谱客的博主 成就鱼,最近开发中收集的这篇文章主要介绍Python将一个文件夹的文件装载到PostgreSQL数据库BLOB列,并将BLOB列下载到另一个文件夹,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
import os
import psycopg2
dir_path = r'C:/Users/Administrator/PycharmProjects/pythonProject9/DownLoadFiles/'
for path in os.scandir(dir_path):
if path.is_file():
print(path.name)
with open(dir_path+path.name, 'rb') as file:
binaryData = file.read()
try:
con = psycopg2.connect(user="postgres",
password="postgres",
host="127.0.0.1",
port="5432",
database="testdb")
cur = con.cursor()
sql_insert_blob_query = """ INSERT INTO bindata
(name, data) VALUES (%s,%s)"""
# Convert data into tuple format
insert_blob_tuple = (path.name, binaryData)
result = cur.execute(sql_insert_blob_query, insert_blob_tuple)
con.commit()
print("Image and file inserted successfully as a BLOB into python_employee table", result)
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL", error)
finally:
# closing database connection.
if (con):
cur.close()
con.close()
print("nPostgreSQL connection is closed")
import psycopg2
dir_path = r'C:/Users/Administrator/PycharmProjects/pythonProject9/DownLoadFiles/'
try:
con = psycopg2.connect(user="postgres",
password="postgres",
host="127.0.0.1",
port="5432",
database="testdb")
cur = con.cursor()
cur.execute("SELECT * from bindata")
records = cur.fetchall()
print("
STUDENT INFORMATION
")
print("-----------------------------------")
for row in records:
print("
id = ", row[0])
print("
name = ", row[1])
print("
data = ", row[2])
"n"
with open(dir_path + row[1], 'wb') as file:
file.write(row[2])
con.commit()
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL", error)
finally:
# closing database connection.
if (con):
cur.close()
con.close()
print("nPostgreSQL connection is closed")
DROP TABLE public.bindata;
CREATE TABLE public.bindata (
id serial4 NOT NULL,
"name" varchar NULL,
"data" bytea NULL
);
最后
以上就是成就鱼为你收集整理的Python将一个文件夹的文件装载到PostgreSQL数据库BLOB列,并将BLOB列下载到另一个文件夹的全部内容,希望文章能够帮你解决Python将一个文件夹的文件装载到PostgreSQL数据库BLOB列,并将BLOB列下载到另一个文件夹所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复