簡體   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