2
我正在試圖製作一個程序,該文件在dbf
文件中進行更改,然後上載它們。我已經閱讀了dbf
文件並將它們上傳到mysql
數據庫,但它的上傳時間爲50分鐘。我試圖讓它只上傳已更改的字段。我遇到的問題是,我似乎需要關閉並重新打開dbf
文件。如果有人在做這件事的時候做出改變,它不會注意到這是一個變化。使用python中的dbf庫讀取更改
是否有這樣做的更好/正道:
import time
import dbf
import MySQLdb
import os
source_path = r"\\path\to\file"
file_name = "\\test.Dbf"
print "Found Source DBF"
source = dbf.Table(source_path + file_name)
source.open()
print "Opened DBF"
updated = list(source)
print "Copied Source"
db = MySQLdb.connect(host = "myHost.com", port=3306, user = "user", passwd = "pass", db = "database")
cur = db.cursor()
print "Connected to database"
try:
cur.execute("DROP TABLE IF EXISTS dbftomysql")
except:
db.rollback()
print "Dropped old table"
sql = """CREATE TABLE table(
col1 VARCHAR(200) NOT NULL,
col2 VARCHAR(200),
col3 VARCHAR(200),
col4 NUMERIC(15,2),
col5 VARCHAR(200))"""
cur.execute(sql)
print "Created new table"
for i, s in zip(source, updated):
query = """INSERT table SET col1 = %s, col2 = %s, col3 = %s, col4 = %s, col5 = %s"""
values = (i["col1"], i ["col2 "], i["col3"], i["col4"], i["col5"])
cur.execute(query, values)
db.commit()
print i["col1"], i ["col2 "], i["col3"], i["col4"], i["col5"]
print "First Upload Completed"
while True:
for i, s in zip(source, updated):
if i["col1"] != s["col1"]:
print i["col1"] + " col1Updated"
query = """UPDATE table SET col1= %s WHERE col1= %s"""
values = (i["col1"], s["col1"])
try:
cur.execute(query, values)
db.commit()
except:
db.rollback()
print "No connection to database"
if i["col2"] != s["col2"]:
print i["col2"] + " col2 Updated for " + i["col1"]
query = """UPDATE table SET col2 = %s WHERE col1= %s OR col1= %s"""
values = (i["col2"], i["col1"], s["col1"])
try:
cur.execute(query, values)
db.commit()
except:
db.rollback()
print "No connection to database"
#ect
updated = list(source)
source.close()
source.open()
time.sleep(0.2)
感謝您的回覆。我補充說,現在我得到一個錯誤。 '元組索引必須是整數,而不是str'。我有點理解它告訴我什麼,但不知道如何實施它。此外,在字段上傳後,我需要做一些類似'[col1'] = i ['col1']' – 2014-12-03 23:19:15
@ChrisMeek:已更新的答案。 – 2014-12-03 23:37:58
非常感謝。 – 2014-12-03 23:40:26