繁体   English   中英

使用 Python for.csv 导入 postgreSQL:消除重复项

[英]Using Python for .csv import into postgreSQL : Eliminate Duplicates

我正在处理的一个项目有一个 .csv 文件,该文件每 10 分钟更新一次。 我想在更新时将该数据读入 SQL。 我已经有一个 powershell 脚本监视 .csv 导入到的 ftp 文件夹。 看门狗powershell启动批处理文件将.csv重命名为固定名称,导入到sql中,然后删除。 下面的代码确实成功地将 .csv 中的值导入到 SQL 表中。 我唯一剩下的就是在批处理文件运行时解析重复项以避免将它们添加到表中。

Python 代码

import csv
import pyodbc

#connect to database
#DB connection string
print("Establishing Database connection...")
con = pyodbc.connect('DSN=testdatabase')
cursor = con.cursor()
print("...Connected to database.")


#read file and copy data into analysis server table
print("Reading file contents and copying into database...")
with open('C:\\Users\\CurrentUser\\Desktop\\test1.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    next(readCSV) #skips the header row
    for row in readCSV: 
        cursor.execute("INSERT INTO testtable (id, year, month, day) VALUES (?, ?, ?, ?)",
            row[0], row[1], row[2], row[3])
        con.commit()
print("...Completed reading file contents and copying into database.")

SQL 表将不断接收数据而不截断,因此使用 MERGE WITH 做一些事情一开始可能效果很好,但几天后很快就会陷入困境,因为代码必须将 .csv 与越来越多的数据进行比较。 我正在考虑将 initial.csv 的最后一行保存到一个单独的文件中,以便稍后调用。 在接下来的 10 分钟导入迭代中,调用该信息并将其与从底部开始的 new.csv 进行比较。 第一个单元格是某种时间戳,因此为了进行比较,我正在考虑从另一个堆栈溢出问题How to compare two timestamps in Python?

from datetime import datetime

timestamp1 = "Feb 12 08:02:32 2015"
timestamp2 = "Jan 27 11:52:02 2014"

t1 = datetime.strptime(timestamp1, "%b %d %H:%M:%S %Y")
t2 = datetime.strptime(timestamp2, "%b %d %H:%M:%S %Y")

difference = t1 - t2

我的时间戳的格式是这样的,

%Y/%m/%d %H:%M:%S.%f

我会提到 powershell 脚本不能很好地处理同时到达 ftp 文件夹的多个文件,所以我有很多数据进入 one.csv。 我的意思是大约 160 多列。 如果没有更好的方法,我非常愿意添加所有列标题和值,但对于 INSERT INTO 格式来说,这是一个很大的问题。

所以总而言之,有没有更好的方法来做我想做的事情? 有没有其他人在我没有重新发明轮子的情况下做过类似的事情? 如果没有更好的方法来做我想做的事情,我的方法听起来合理吗? 非常感激。

import csv
import pyodbc
import time
from datetime import datetime

#connect to database
#DB connection string
print("Establishing Database connection...")
con = pyodbc.connect('DSN=SQLdatabase')
cursor = con.cursor()
print("...Connected to database.")

#recall last timestamp entry in db table

t1 = datetime.strptime(cursor.execute("SELECT MAX(id) FROM test;").fetchval(), "%Y/%m/%d %H:%M:%S.%f")


#read file and copy data into table
print("Reading file contents and copying into table...")
with open('C:\\Users\\user\\Desktop\\test2.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    columns = next(readCSV) #skips the header row
    t2 = datetime.strptime(next(readCSV)[0], "%Y/%m/%d %H:%M:%S.%f")
    while t2 < t1:
        t2 = datetime.strptime(next(readCSV)[0], "%Y/%m/%d %H:%M:%S.%f")
    query = 'insert into test({0}) values ({1})'
    query = query.format(','.join(columns), ','.join('?' * len(columns)))
    for data in readCSV:
        cursor.execute(query, data)
    con.commit()
print("Data posted to table")
    

这就是我结束的地方。 运行良好,无需将标头放入“插入”表达式中。 跳过暂存表,只将 .csv 的内容保存在一个数组中,直到剩余的代码确定需要添加的内容。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM