使用元组执行SQLite3插入语句时遇TypeError问题求助
问题描述
从CSV提取的数据顺序与SQLite3插入语句要求不符,需将数据插入两个不同的表。尝试用元组精准获取每一项数据(例如FirstName来自row[2]),但执行时触发错误:TypeError: tuple indices must be integers or slices, not tuple
报错代码行:
values(?,?,?,?,?,?,?,?)''',r[0],r[2],r[1],r[3],r[4],r[7],r[8,],r[9])
完整代码
#!/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])
解决步骤
1. 修复语法错误
报错的直接原因是r[8,]多了个逗号,变成了元组类型的索引((8,)是元组),改成r[8]即可。
2. 修正execute方法的参数传递
sqlite3.Cursor.execute()的第二个参数要求是单个序列(元组/列表),不能传入多个分散的参数。正确做法是把需要的字段按插入顺序打包成一个元组传入:
错误写法:
curs.execute(sql, r[0], r[2], r[1], r[3], r[4], r[7], r[8], r[9])
正确写法:
# 按插入顺序打包需要的字段 insert_values = (r[0], r[2], r[1], r[3], r[4], r[7], r[8], r[9]) curs.execute('''insert into people (id,firstname,lastname,email,major,city,state,zip) values(?,?,?,?,?,?,?,?)''', insert_values)
也可以直接从row中提取对应字段,省去转存r的步骤:
insert_values = (row[0], row[2], row[1], row[3], row[4], row[7], row[8], row[9]) curs.execute(sql, insert_values)
3. 处理第二个表的插入(courses)
如果要插入courses表,同样提取对应字段打包成元组,执行另一条INSERT语句即可。示例如下(需根据实际CSV字段对应关系调整索引):
# 假设courses表字段对应row中的这些索引 course_values = (row[0], row[5], row[6], row[xx]) # 替换xx为实际索引 curs.execute('''insert into courses (id, subjcode, coursenumber, termcode) values(?,?,?,?)''', course_values)
4. 事务提交与资源关闭
循环结束后必须提交事务,避免数据丢失;同时要关闭游标和数据库连接:
newdb.commit() curs.close() newdb.close()
优化后的完整代码示例
#!/usr/bin/python import sqlite3 import csv import sys inFile = 'mod5csv.csv' outFile = 'test.db' # 创建数据库连接 newdb = sqlite3.connect(outFile) curs = newdb.cursor() # 重建表 curs.execute('''drop table if exists courses''') curs.execute('''drop table if exists people''') 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 text, coursenumber text, termcode text)''') # 读取CSV并插入数据 try: with open(inFile, 'r') as f: reader = csv.reader(f, delimiter=',', quotechar='"') next(reader) # 直接跳过表头,替代counter计数方式更简洁 for row in reader: # 插入people表 people_vals = (row[0], row[2], row[1], row[3], row[4], row[7], row[8], row[9]) curs.execute('''insert into people (id,firstname,lastname,email,major,city,state,zip) values(?,?,?,?,?,?,?,?)''', people_vals) # 插入courses表,根据实际CSV字段对应调整索引 courses_vals = (row[0], row[5], row[6], row[10]) # 替换为实际对应的索引 curs.execute('''insert into courses (id, subjcode, coursenumber, termcode) values(?,?,?,?)''', courses_vals) # 提交事务 newdb.commit() except Exception as e: print(f"处理出错: {str(e)}") newdb.rollback() # 出错时回滚事务 finally: # 关闭资源 curs.close() newdb.close()
内容的提问来源于stack exchange,提问作者RMach
相关产品推荐
相关产品推荐

