2013-03-08 77 views
1

改變的MS Access表名,我有幾個MS Access數據庫,每有一個名爲PlotStatus-name-3/13/12表。是否有可能與蟒蛇

我需要每個表中導入到.csv表。如果我手動更改表的名稱PlotStatus_name_3_13_12,此代碼的工作。 有誰知道如何使用Python更改表namees?

#connect to access database 
for filename in os.listdir(prog_rep_local): 
if filename[-6:] == ".accdb": 
    DBtable = os.path.join(prog_rep_local, filename) 
    conn = pyodbc.connect(r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=' + DBtable) 
    cursor = conn.cursor() 
    ct = cursor.tables 
    for row in ct(): 
     rtn = row.table_name 
     if rtn[:10] == "PlotStatus": 

      #this does not work: 
      #Oldpath = os.path.join(prog_rep_local, filename, rtn) 
      #print Oldpath 
      #fpr = Oldpath.replace('-', '_')#.replace("/","_") 
      #print fpr 
      #newname = os.rename(Oldpath, fpr) this does not work 
      #print newname 
      #spqaccdb = "SELECT * FROM " + newname 


      #this workds if I manually change the table names in advance 
      sqlaccdb = "SELECT * FROM " + rtn 
      print sqlaccdb 

      cursor.execute(sqlaccdb) 
      rows = cursor.fetchall() 

回答

1

更簡單的解決辦法是隻需添加周圍的表名方括號,以便/ s的不甩開SQL命令解釋器。

sqlaccdb = "SELECT * FROM [" + rtn + "]" 
+0

謝謝!因爲我沒有點名譽,我不能給予好評你。 – user15042 2013-03-18 16:55:11