我有几个 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()
最佳答案
一个更简单的解决方案是在表名周围添加括号,这样/s 就不会影响 SQL 命令解释器。
sqlaccdb = "SELECT * FROM [" + rtn + "]"
关于python - 是否可以使用python更改ms access表名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15304779/