1

I have a very simple code in python, basically I try to create indexes for each table in my database (already exists). The database and my script file are located at the same folder. After fetching a list of names of the tables and trying to create indexes for the first table, I get this error message:

c.execute("CREATE INDEX IF NOT EXISTS "+tableName[m]+"Date ON "+tableName[m]+" (date)"); sqlite3.OperationalError: no such table: main.m

The database doesn't have any table with this name (main.m)!

my code:

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()

Thanks for your help!

Shadow
  • 33,525
  • 10
  • 51
  • 64
Zryan
  • 115
  • 1
  • 8

1 Answers1

1

If the tableName variable shows the correct table names as per your comment, then just use tableName when you create the sql statement instead of 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)");  
Shadow
  • 33,525
  • 10
  • 51
  • 64