我在python中有一个非常简单的代码,基本上我尝试为数据库中的每个表创建索引(已经存在)。数据库和我的脚本文件位于同一文件夹。在获取表名称列表并尝试为第一个表创建索引后,我得到以下错误消息:
c.execute("CREATE INDEX IF NOT EXISTS "+tableName[m]+"Date ON "+tableName[m]+" (date)"); sqlite3.OperationalError:没有这样的表:main.m
c.execute("CREATE INDEX IF NOT EXISTS "+tableName[m]+"Date ON "+tableName[m]+" (date)")
该数据库没有任何具有此名称(main.m)的表!
我的代码:
import sqlite3 DBname = 'myDatabase.sqlite'; # connect to the database conn = sqlite3.connect(DBname); c = conn.cursor(); c.execute("SELECT name FROM sqlite_master WHERE type='table'"); tables = c.fetchall(); print("\nCreating the indices for each table in the database ..."); for m in range (0,len(tables)): tableName = tables[m][0]; print(tableName) c.execute("CREATE INDEX IF NOT EXISTS "+tableName[m]+"Date ON "+tableName[m]+" (date)"); c.execute("CREATE INDEX IF NOT EXISTS "+tableName[m]+"Year ON "+tableName[m]+" (year)"); conn.close()
谢谢你的帮助!
如果tableName变量根据您的注释显示正确的表名,则仅tableName在创建sql语句时使用,而不是tableName[m]:
tableName
tableName[m]
c.execute("CREATE INDEX IF NOT EXISTS "+tableName+"Date ON "+tableName+" (date)"); c.execute("CREATE INDEX IF NOT EXISTS "+tableName+"Year ON "+tableName+" (year)");