环顾四周之后,我编写了这个插入/检索代码来读取.mat文件,将其发送到bytea postgres数据库列,然后尝试检索它并重新创建文件。
我使用psycopg2进行数据库交互。
插入:
full_file_path = os.path.join( folder_path, single_file ) f = open(full_file_path,'rb') file_data = psycopg2.Binary( f.read() ) cur.execute( "INSERT INTO file_data_table " "( id, file_name, file_data, insertion_date) " "VALUES ( DEFAULT, %s, %s, %s)", (single_file, file_data, timestamp)) f.close() conn.commit() print single_file + " inserted"试图检索并将其保存到文件(file_name是“something.mat”)
cur = conn.cursor() cur.execute( "SELECT encode( file_data, 'hex' ), file_name FROM file_data_table") result = cur.fetchall() print result[0][0] for row in result: print row[1] full_file_path = os.path.join(folder_path, row[1]) f = open(full_file_path,'w') f.write(row[0]) f.close()它从数据库中检索数据并成功将其保存在文件中,但该文件未作为mat文件打开,文件大小比我试图存储在数据库中的原始文件大得多(大约两倍) 。
我假设发生了一些数据转换,我没有正确处理。
非常感谢任何帮助。
After looking around, I wrote this insertion/retrieval code to read in a .mat file, send it off to a bytea postgres database column, and then try and retrieve it and recreate the file.
I use psycopg2 for database interaction.
Insertion:
full_file_path = os.path.join( folder_path, single_file ) f = open(full_file_path,'rb') file_data = psycopg2.Binary( f.read() ) cur.execute( "INSERT INTO file_data_table " "( id, file_name, file_data, insertion_date) " "VALUES ( DEFAULT, %s, %s, %s)", (single_file, file_data, timestamp)) f.close() conn.commit() print single_file + " inserted"Trying to retrieve and save it to file( the file_name is "something.mat" )
cur = conn.cursor() cur.execute( "SELECT encode( file_data, 'hex' ), file_name FROM file_data_table") result = cur.fetchall() print result[0][0] for row in result: print row[1] full_file_path = os.path.join(folder_path, row[1]) f = open(full_file_path,'w') f.write(row[0]) f.close()It retrieves data from the database and successfully saves it in a file, but the file doesn't open as a mat file, and the file size is much larger( roughly twice as big ) as the original file I tried to store in the database.
I assume some data transformation is happening that I am not handling properly.
Any assistance is greatly appreciated.
最满意答案
使用Josh Kupershmidt的提示,我弄清楚出了什么问题。
通过删除编码并将检索到的缓冲区转换为字符串,它现在似乎工作。
cur = conn.cursor() cur.execute( "SELECT file_data, file_name FROM file_data_table") result = cur.fetchall() print result[0][0] for row in result: print row[1] full_file_path = os.path.join(folder_path, row[1]) f = open(full_file_path,'w') f.write(str(row[0])) f.close()Using Josh Kupershmidt's tip, I figured out what was wrong.
By removing the encode and converting the retrieved buffer to a string, it seems to work now.
cur = conn.cursor() cur.execute( "SELECT file_data, file_name FROM file_data_table") result = cur.fetchall() print result[0][0] for row in result: print row[1] full_file_path = os.path.join(folder_path, row[1]) f = open(full_file_path,'w') f.write(str(row[0])) f.close()更多推荐
发布评论