简体   繁体   English

使用 psycopg2 从 csv 文件创建 Postgresql 表

[英]Create Postgresql table from csv file using psycopg2

Hi I looking for solutions that let me create table from csv files.嗨,我正在寻找让我从 csv 文件创建表的解决方案。 I find solution on another forum.我在另一个论坛上找到了解决方案。 This code looks like this:此代码如下所示:

import csv
import psycopg2
import os
import glob


conn = psycopg2.connect("host= localhost port=5433  dbname=testDB user= postgres password= ************")
print("Connecting to Database")

cur = conn.cursor()
csvPath = "W:\Maciej.Olech\structure_files"

# Loop through each CSV
for filename in glob.glob(csvPath+"*.csv"):
# Create a table name
    tablename = filename.replace("W:\Maciej.Olech\structure_files", "").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.execute(sqlQueryCreate)
conn.commit()
cur.close()

I try to run this code but i get this error:我尝试运行此代码,但出现此错误:

C:\Users\MACIEJ~1.OLE\AppData\Local\Temp/ipykernel_5320/1273240169.py in <module>
     40         sqlQueryCreate += ");"
     41 
---> 42 cur.execute(sqlQueryCreate)
     43 conn.commit()
     44 cur.close()

NameError: name 'sqlQueryCreate' is not defined

I don't understand why i have this error becouse sqlQueryCreate is defined.我不明白为什么我有这个错误,因为定义了 sqlQueryCreate。 Any one have idea what is wrong?有人知道出了什么问题吗? Thanks for any help.谢谢你的帮助。

There are a few issues with your code.您的代码存在一些问题。

  1. In Windows, paths need to have the \ escaped.在 Windows 中,路径需要转义\
  2. your cur.execute(sqlQueryCreate) and conn.commit() are indented wrong.您的cur.execute(sqlQueryCreate)conn.commit()缩进错误。 ditto with sqlQueryCreate = sqlQueryCreate[:-2] and sqlQueryCreate += ");"同上sqlQueryCreate = sqlQueryCreate[:-2]sqlQueryCreate += ");"
  3. Edit: Realized that your glob.glob() parameter isn't correct.编辑:意识到您的 glob.glob() 参数不正确。 What you intend: W:\\Jan.Bree\\structure_files\\*.csv , what you actually had W:\\Jan.Bree\\structure_files*.csv您的意图: W:\\Jan.Bree\\structure_files\\*.csv ,您实际拥有的W:\\Jan.Bree\\structure_files*.csv
import csv
import psycopg2
import os
import glob


conn = psycopg2.connect("host= localhost port=5433  dbname=testDB user= postgres password= ************")
print("Connecting to Database")

cur = conn.cursor()
csvPath = "W:\\Jan.Bree\\structure_files"

# Loop through each CSV
for filename in glob.glob(os.path.join(csvPath,"*.csv")):
# Create a table name
    tablename = filename.replace("W:\\Jan.Bree\\structure_files", "").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.execute(sqlQueryCreate)
    conn.commit()

cur.close()

This should cover the issues;这应该涵盖这些问题; but I have no way of testing the code as I don't use psycopg2.但我无法测试代码,因为我不使用 psycopg2。 I'm assuming that the connect() works.我假设 connect() 有效。

You do too much work, there is the Alchemy library and things are done quickly and painlessly.你做了太多的工作,有炼金术库,事情可以快速轻松地完成。

import pandas as pd
from sqlalchemy import create_engine
import psycopg2

df = pd.read_csv('W:\Maciej.Olech\structure_files.csv', sep=',')



##> {dialect}+{driver}://{user}:{password}@{host}:{port}/{database}
# database = bazakot22
# user = foka2
# password = #gg3Ewampkl
# host = 127.0.0.1
# port= 5432


engine = create_engine('postgresql://foka2:#gg3Ewampkl@127.0.0.1:5432/bazakot22')

df.to_sql("table_name4", engine)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用psycopg2从csv文件动态创建表 - Dynamically creating table from csv file using psycopg2 Postgresql:如何使用psycopg2将表中的列复制到另一个? - Postgresql: how to copy a column from a table to another using psycopg2? 使用psycopg2从Postgresql中基于模式的表中选择数据 - Selecting data from schema based table in Postgresql using psycopg2 使用 psycopg2 从 PostgreSQL 中基于模式的表中选择数据 - Selecting data using psycopg2 from a schema based table in PostgreSQL 使用psycopg2查询将数据从表复制到csv文件 - Use psycopg2 query to copy data from a table to a csv file 如何使用psycopg2将特定列从CSV文件复制到postgres表? - how to copy specific columns from CSV file to postgres table using psycopg2? 我无法通过从列表中获取列名来创建表?(postgresql/psycopg2) - I can't create table by getting column names from a list?(postgresql/psycopg2) 使用 psycopg2 删除名称中带有引号的 postgreSQL 表 - drop postgreSQL table with Quotation Marks in name using psycopg2 Python / PostgreSQL - 如何使用psycopg2库将表复制到另一个表? - Python / PostgreSQL - How to copy a table to another using the psycopg2 library? 使用psycopg2而没有SQLAlchemy的Pandas数据帧到PostgreSQL表? - Pandas dataframe to PostgreSQL table using psycopg2 without SQLAlchemy?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM