如何使用 python 基于 CSV 自动创建 table 到 postgres

how to automatically create table based on CSV into postgres using python

我是一名新 Python 程序员,正在尝试使用 python 脚本将示例 CSV 文件导入我的 Postgres 数据库。
我有名称为 abstable1 的 CSV 文件,它有 3 headers:

absid, name, number I have many such files in a folder I want to create a table into PostgreSQL with the same name as the CSV file for all.

这是我试图为一个要测试的文件创建 table 的代码:

import psycopg2
import csv
import os

#filePath = 'c:\Python27\Scripts\abstable1.csv'
conn = psycopg2.connect("host= hostnamexx dbname=dbnamexx user= usernamexx password= pwdxx")
print("Connecting to Database")
cur = conn.cursor()

#Uncomment to execute the code below to create a table
cur.execute("""CREATE TABLE abs.abstable1(
absid varchar(10) PRIMARY KEY,
name integer,
number integer 
)
 """)
#to copy the csv data into created table
with open('abstable1.csv', 'r') as f:
    next(f)
    cur.copy_from(f, 'abs.abstable1', sep=',')
conn.commit()
conn.close()

这是我遇到的错误:

File "c:\Python27\Scripts\testabs.py", line 26, in <module>
    cur.copy_from(f, 'abs.abstable1', sep=',')
psycopg2.errors.QueryCanceled: COPY from stdin failed: error in .read() call: exceptions.ValueError Mixing iteration and read methods would lose data
CONTEXT:  COPY abstable1, line 1

非常感谢任何解决此问题的建议或替代解决方案。

我试过你的代码并且工作正常

import psycopg2

conn = psycopg2.connect("host= 127.0.0.1 dbname=testdb user=postgres password=postgres")
print("Connecting to Database")
cur = conn.cursor()

'''cur.execute("""CREATE TABLE abstable1(
absid varchar(10) PRIMARY KEY,
name integer,
number integer 
)
""")'''

with open('lolo.csv', 'r') as f:
    next(f)
    cur.copy_from(f, 'abstable1', sep=',', columns=('absid', 'name', 'number'))

conn.commit()
conn.close()

尽管我必须进行一些更改才能使其正常工作: 我不得不命名 table abstable1 因为使用 abs.abstable1 postgres 假设我正在使用模式 abs,如果不检查它,也许你在数据库上创建了该模式,我也在使用 python 3.7 我注意到您正在使用 python 2.7(我认为它不再受支持),这可能会导致问题,因为您说您正在学习 我建议您使用 python 3,因为它更常用现在,您很可能会遇到写在上面的代码,您必须调整代码以适应您的 python 2.7

以下是对我有用的方法:import glob

此代码自动读取 文件夹中的所有 CSV 文件,并创建一个 table 与文件同名的文件。 尽管我仍在尝试弄清楚如何根据 CSV 中的数据提取特定的数据类型。 但就 table 创建而言,这对一个文件夹中的所有 CSV 文件来说就像一个魅力。

import csv
import psycopg2
import os
import glob


conn = psycopg2.connect("host= hostnamexx dbname=dbnamexx user= usernamexx password= 
pwdxx")
print("Connecting to Database")

csvPath = "./TestDataLGA/"

# Loop through each CSV
for filename in glob.glob(csvPath+"*.csv"):
# Create a table name
tablename = filename.replace("./TestDataLGA\", "").replace(".csv", "")
print tablename

# Open file
fileInput = open(filename, "r")

# Extract first line of file
firstLine = fileInput.readline().strip()


# Split columns into an array [...]
columns = firstLine.split(",")
     

# Build SQL code to drop table if exists and create table
sqlQueryCreate = 'DROP TABLE IF EXISTS '+ tablename + ";\n"
sqlQueryCreate += 'CREATE TABLE'+ tablename + "("

#some loop or function according to your requiremennt
# Define columns for table
for column in columns:
    sqlQueryCreate += column + " VARCHAR(64),\n"

sqlQueryCreate = sqlQueryCreate[:-2]
sqlQueryCreate += ");"

cur = conn.cursor()
cur.execute(sqlQueryCreate)
conn.commit()
cur.close()