是否可以用Python更改MS Access表名称?

1 投票
1 回答
676 浏览
提问于 2025-04-17 18:28

我有几个ms access数据库,每个数据库里都有一个叫做 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 个回答

3

一个更简单的解决办法就是在表名周围加上括号,这样斜杠就不会影响SQL命令的解析了。

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

撰写回答