是否可以使用python更改ms访问表名称

时间:2013-03-08 23:00:42

标签: python ms-access

我有几个ms访问数据库,每个数据库都有一个名为PlotStatus-name-3/13/12的表。

我需要将每个表导入.csv表。如果我手动将表名更改为PlotStatus_name_3_13_12,则此代码有效。 有谁知道如何使用python更改表名?

#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 个答案:

答案 0 :(得分:1)

更简单的解决方案是在表名周围添加括号,以便/ s不会抛弃SQL命令解释器。

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