我试图编写一个脚本,在Postgres数据库中创建一个新表,并使用psycopg2库将现有的csv文件复制到该表中。为了明确起见,我严格地尝试用psycopg2
来实现这一点,而不是使用其他方法,比如psql.exe
或ogr2ogr.
,我可以连接、创建表,并对现有的表进行测试查询。*注:该数据库有多个模式。我创建了一个名为'test‘的表。
import os
import sys
import csv
import psycopg2
from os import path
from datetime import datetime
csv_file = r"C:\Projects\csv_report_to_sql\test\csv_report.csv"
conn = psycopg2.connect(dbname='mydb', user='postgres', password='mypassword', host='www.mydbserver.com', port='5432', sslmode='require')
cur = conn.cursor()
cur.execute("""
CREATE TABLE test.new_table
(
region TEXT,
state TEXT,
tier TEXT,
v_detailed DOUBLE PRECISION,
v_approx DOUBLE PRECISION,
v_unmapped DOUBLE PRECISION,
v_total DOUBLE PRECISION,
a_detailed DOUBLE PRECISION,
a_approx DOUBLE PRECISION,
a_unmapped DOUBLE PRECISION,
a_total DOUBLE PRECISION
)
""")
conn.commit()
现在我可以在我的test
模式下看到表,但是要在脚本中测试它,我可以运行:
cur.execute('SELECT * FROM test.new_table')
one = cur.fetchone()
print(one)
它返回"None",并将其更正为空表。现在,我想将csv文件数据复制到这个新表中。我是psycopg2
的新手,但是从这个tutorial,我假设我必须建立一个新的连接,因为旧的连接被关闭。
conn = psycopg2.connect(dbname='mydb', user='postgres', password='mypassword', host='www.mydbserver.com', port='5432', sslmode='require')
cur = conn.cursor()
with open(csv_file, 'r') as f:
next(f) # Skip the header row.
cur.copy_from(f, 'test.new_table', sep=',')
conn.commit()
当我运行上面的代码时,我会得到以下错误:
UndefinedTable:关系"new_table“不存在
我能清楚地看到桌子的存在,那么我在这里做错了什么呢?
发布于 2021-12-09 23:48:32
好的,这是一个奇怪的修复,但我想这可能与在木星笔记本中单独运行它有关。基本上,我只是把所有的东西组合在一起(移除建议的第二个连接)在一个单元格中,它就正常运行了。假设在独立脚本中运行它没有问题。
import os
import sys
import psycopg2
import csv
csv_file = r"C:\Projects\csv_report_to_sql\test\csv_report.csv"
conn = psycopg2.connect(dbname='mydb', user='postgres', password='mypassword',
host='www.mydbserver.com', port='5432', sslmode='require')
cur = conn.cursor()
cur.execute("""
CREATE TABLE test.new_table
(
region TEXT,
state TEXT,
tier TEXT,
v_detailed DOUBLE PRECISION,
v_approx DOUBLE PRECISION,
v_unmapped DOUBLE PRECISION,
v_total DOUBLE PRECISION,
a_detailed DOUBLE PRECISION,
a_approx DOUBLE PRECISION,
a_unmapped DOUBLE PRECISION,
a_total DOUBLE PRECISION
)
""")
conn.commit()
with open(csv_file, 'r') as f:
next(f) # Skip the header row.
cur.copy_from(f, 'test.new_table', sep=',')
conn.commit()
conn.close()
https://stackoverflow.com/questions/70247424
复制相似问题