簡體   English   中英

psycopg:無法使用python從csv復制到postgresql,沒有結果

[英]psycopg: can't copy from csv to postgresql with python, no results

我有帶oid的簡單postgresql數據庫。 列數及其名稱類似於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) 

這是我的數據庫創建:

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

感謝您更新問題。 在列名中有空格是有點不尋常的,盡管並非不可能。 我嘗試直接從psql命令行輸入您的復制行。 有效。 然后它跳到我身上:

for line in csv_file:
    print(line)

csv_file.seek(0)

從文件中打印數據時,將移動文件指針。 seek(0)將其重置為開始。 如果添加查找,則該命令應該起作用,或者只是消除打印文件內容的循環。

-G

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM