Home > Software engineering >  How to execute sqlite3 insert statement with a tuple, receiving TypeError: tuple indices must be int
How to execute sqlite3 insert statement with a tuple, receiving TypeError: tuple indices must be int

Time:10-04

So, I have data pulled from a CSV that is not in the right order for the execute Insert Statement and will need to be inserted into two different tables. I'm trying to insert into the database using a Tuple to access each specific piece accurately. Such as FirstName comes from row[2] etc. I'm a total newb when it comes to this and have spent days researching on this site and many others... What is the right way to do a For Loop from CSV data, inserting it into a Database using SQLITE3 with a tuple?

Currently, I get the error: line 49, in values(?,?,?,?,?,?,?,?)''',r[0],r[2],r[1],r[3],r[4],r[7],r[8,],r[9]) TypeError: tuple indices must be integers or slices, not tuple

Here is my current code:

#!/usr/bin/python
# import modules
import sqlite3
import csv
import sys

# Get input and output names
#inFile = sys.argv[1]
#outFile = sys.argv[2]
inFile = 'mod5csv.csv'
outFile = 'test.db'



# Create DB 
newdb = sqlite3.connect(str(outFile))

# If tables exist already then drop them
curs = newdb.cursor()
curs.execute('''drop table if exists courses''')
curs.execute('''drop table if exists people''')

#Create table
curs.execute('''create table people
        (id text, lastname text, firstname text, email text, major text, city text, state text, zip text)''')

#curs.execute('''create table courses
#        (id text, subjcode txt, coursenumber text, termcode text)''')

# Try to read in CSV
try:
    reader = csv.reader(open(inFile, 'r'), delimiter = ',', quotechar='"')
except:
    print("Sorry "   str(inFile)    " is not a valid CSV file.")
    exit(1)


counter = 0
for row in reader:
    counter  = 1
    if counter == 1:
      continue
    r = (row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9])
    if counter == 5:
        print(row[1])
        print(counter)
    #print(row[counter][2])
    curs.execute('''insert into people (id,firstname,lastname,email,major,city,state,zip)
    values(?,?,?,?,?,?,?,?)''',r[0],r[2],r[1],r[3],r[4],r[7],r[8,],r[9])

CodePudding user response:

Notice r[8,]. Its easy to mistype a comma which turns an integer into a 1-tuple holding that integer. When the error is tuple indices must be integers or slices, not tuple and you are sure you typed in an integer literal, that's usually the problem.

Adding whitespace to your code can help spot the problem.

    curs.execute('''insert into people 
        (id,firstname,lastname,email,major,city,state,zip)
        values(?,?,?,?,?,?,?,?)''',
        r[0], r[2], r[1], r[3], r[4], r[7], r[8], r[9])
  • Related