我有一个简单的postgresql db with oid。列数及其名称与csv文件中的标题类似。 我正在尝试使用复制命令:
def db_copy_images(self, file):
my_file = open(file)
try:
self.process_file('images_original', my_file)
finally:
pass
def process_file(self, table, csv_file):
dbname = 'v'
user = 'on'
password = 'on'
host = 'ip'
port = 5432
SQL_STATEMENT = """COPY %s FROM STDIN WITH DELIMITER AS '|' CSV HEADER"""
print ("OK")
conn = psycopg2.connect(database=dbname,user=user,password=password,host=host,port=port)
cursor = conn.cursor()
for line in csv_file:
print(line)
#cursor.copy_expert(sql = SQL_STATEMENT % table, file = csv_file)
cursor.copy_expert("COPY images_original FROM STDIN WITH DELIMITER AS '|' CSV HEADER", file = csv_file)
cursor.execute("COMMIT;")
我得到一个行列表作为输出,然后我的过程就完成了。但是数据库没有变化,也没有错误。我该怎么调试呢?这是我的--trace:
manager_db.py(63): cursor.copy_expert("COPY images_original FROM STDOUT WITH DELIMITER AS '|' CSV HEADER", file = csv_file)
manager_db.py(66): cursor.execute("COMMIT;")
manager_db.py(68): conn.commit
manager_db.py(69): cursor.close
manager_db.py(70): conn.close
manager_db.py(36): pass
--- modulename: trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)
这是我的db create:
CREATE TABLE images_original
(
"image id" integer NOT NULL,
"file url" character varying NOT NULL,
"file format id" integer,
"file format" character varying,
"file width" integer,
"file height" integer,
"file quality factor" integer,
"file bit depth" integer,
"file margin" integer,
"file bg color" integer,
"file size" integer,
"scaling factor" character varying,
delta character varying
)
WITH (
OIDS=TRUE
);
ALTER TABLE images_original
OWNER TO on;
和测试文件中的第一行:
image id|file url|file format id|file format|file width|file height|file quality factor|file bit depth|file margin|file bg color|file size|scaling factor|delta
172317239|http://cps-static.r.com/2/Open/NBC/The%20Office/Steve%20Carell%204.jpg|0||2336|3504|||||949406||INS
172317239|http://cps-static.r.com/2/Open/NBC/The%20Office/_derived_jpg_q90_0x200_m0/Steve%20Carell%204.jpg|1391886|jpg|133|200|90|24|0|24|6624|5.69|INS
172317239|http://cps-static.r.com/2/Open/NBC/The%20Office/_derived_jpg_q90_155x235_m0/Steve%20Carell%204.jpg|1391887|jpg|155|232|90|24|0|24|8092|6.64|INS
答案 0 :(得分:1)
感谢您更新问题。在列名中有空格有点不寻常,但并非不可能。我尝试直接从psql命令行输入你的拷贝行。有效。然后它跳了出来:
for line in csv_file:
print(line)
csv_file.seek(0)
从文件中打印数据时,移动文件指针。 seek(0)将其重置为开头。如果添加搜索,此命令应该有效,或者只是消除打印文件内容的循环。
-g